LESSON 19 OF 22

19. Automated Tests and Architectural Testability

Validate domain rules, application service workflows, and API behavior with automated tests; mock repository dependencies and build a testable Clean Architecture solution with Dependency Injection.

35 dk 93

Introduction

One of the most important benefits of Clean Architecture is the ability to test business rules and use cases without starting a database, HTTP server, or real external service. In this lesson, we will test domain rules, application service behavior, and API endpoints. We will also mock repository dependencies so that tests remain fast, isolated, and repeatable.

Testability does not simply mean adding a test project. A class must receive its dependencies through its constructor, business logic should not be scattered across controllers, and layers should communicate through contracts. The Domain, Application, Infrastructure, and API layers created in earlier lessons support these goals.

Test types and responsibilities

Each test type has a different purpose. Organizing tests according to their scope prevents unnecessary slowdowns and brittle test suites.

Test typeWhat it validatesDependency strategy
Domain unit testEntity and value object rulesNo external dependencies
Application unit testUse case and service workflowsMock or fake repositories
API integration testHTTP, routing, model binding, and middlewareTest server and controlled infrastructure

Unit tests should usually run in milliseconds, avoid external systems, and return the same result for the same inputs. Integration tests verify that multiple components work together. Therefore, it is usually better to choose a unit test whenever a behavior can be verified without infrastructure, and reserve integration tests for boundaries that genuinely need to be exercised together.

Adding test projects to the solution

Separating tests from production projects helps control dependencies. For example, the solution can contain the following projects:

dotnet new xunit -n Shop.Domain.Tests
dotnet new xunit -n Shop.Application.Tests
dotnet new xunit -n Shop.Api.Tests

dotnet add Shop.Domain.Tests reference Shop.Domain
dotnet add Shop.Application.Tests reference Shop.Application
dotnet add Shop.Api.Tests reference Shop.Api

The Application test project should preferably not reference Infrastructure directly. This allows use cases to be tested without a real DbContext or SQL Server. The API integration test project references the API project and the packages required to create a test host.

Testing domain rules

Domain tests are the most isolated tests in the solution. Whether an entity rejects an invalid state or an operation raises an exception when a business rule is violated can be tested directly. Test names should explain the method, scenario, and expected result.

using Xunit;

public class ProductTests
{
    [Fact]
    public void Create_WithNegativePrice_ThrowsDomainException()
    {
        // Arrange
        const decimal invalidPrice = -1m;

        // Act
        var action = () => Product.Create("Keyboard", invalidPrice);

        // Assert
        Assert.Throws<DomainException>(action);
    }

    [Fact]
    public void ChangePrice_WithValidValue_UpdatesPrice()
    {
        // Arrange
        var product = Product.Create("Keyboard", 100m);

        // Act
        product.ChangePrice(125m);

        // Assert
        Assert.Equal(125m, product.Price);
    }
}

These tests do not start EF Core, HTTP, or the dependency injection container. That is not a limitation; it demonstrates that the behavior belongs to the domain class itself. Instead of testing private methods directly, test public behavior that uses those private implementation details.

Testing an application service with a mocked repository

An application service depends on a repository contract. During testing, a controlled mock can replace the real repository so that we can verify how the service handles repository results and whether it makes the expected calls. The following example uses Moq with xUnit.

using Moq;
using Xunit;

public class ProductServiceTests
{
    [Fact]
    public async Task GetByIdAsync_WhenProductExists_ReturnsProductDto()
    {
        // Arrange
        var productId = Guid.NewGuid();
        var product = Product.Create("Keyboard", 100m);
        var repository = new Mock<IProductRepository>();

        repository
            .Setup(x => x.GetByIdAsync(productId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(product);

        var service = new ProductService(repository.Object);

        // Act
        var result = await service.GetByIdAsync(
            productId,
            CancellationToken.None);

        // Assert
        Assert.NotNull(result);
        Assert.Equal("Keyboard", result.Name);
        Assert.Equal(100m, result.Price);
        repository.Verify(
            x => x.GetByIdAsync(productId, It.IsAny<CancellationToken>()),
            Times.Once);
    }

    [Fact]
    public async Task GetByIdAsync_WhenProductDoesNotExist_ThrowsNotFoundException()
    {
        // Arrange
        var productId = Guid.NewGuid();
        var repository = new Mock<IProductRepository>();

        repository
            .Setup(x => x.GetByIdAsync(productId, It.IsAny<CancellationToken>()))
            .ReturnsAsync((Product?)null);

        var service = new ProductService(repository.Object);

        // Act
        var action = () => service.GetByIdAsync(
            productId,
            CancellationToken.None);

        // Assert
        await Assert.ThrowsAsync<NotFoundException>(action);
    }
}

The Arrange, Act, Assert structure is explicit. The goal is not to verify the repository's internal query. The goal is to verify how the service processes the repository result. The Verify call checks that the expected repository method was called with the correct identifier and exactly once.

The difference between mocks, stubs, and fakes

  • Stub: Supplies predefined data to the system under test.
  • Mock: Verifies whether a dependency was called and how it was called.
  • Fake: Provides a simpler working implementation, such as an in-memory repository.

Not every test needs interaction verification. Excessive Verify calls make tests depend on implementation details. The priority should be verifying meaningful behavior and results visible to the caller.

Testing API controller behavior

For controller unit tests, the goal is to verify that the controller calls the correct service and maps the result to the appropriate HTTP response. Business rules should not be implemented inside controllers. In the following example, the application service is mocked and a successful GET request is tested.

using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;

public class ProductsControllerTests
{
    [Fact]
    public async Task GetById_WhenProductExists_ReturnsOkWithDto()
    {
        // Arrange
        var productId = Guid.NewGuid();
        var dto = new ProductDto(productId, "Keyboard", 100m);
        var service = new Mock<IProductService>();

        service
            .Setup(x => x.GetByIdAsync(productId, It.IsAny<CancellationToken>()))
            .ReturnsAsync(dto);

        var controller = new ProductsController(service.Object);

        // Act
        var result = await controller.GetById(
            productId,
            CancellationToken.None);

        // Assert
        var okResult = Assert.IsType<OkObjectResult>(result);
        var actual = Assert.IsType<ProductDto>(okResult.Value);
        Assert.Equal(productId, actual.Id);
    }
}

This test does not verify routing, authentication middleware, or JSON serialization. Those concerns belong to API integration tests. A controller unit test should remain focused and check only the conversion from an application result to an HTTP result.

API integration testing with WebApplicationFactory

To test API behavior through the real application pipeline, use WebApplicationFactory<TEntryPoint>. It creates a test host and allows requests to be sent through an HttpClient. Routing, model binding, authorization, exception middleware, and response serialization can then be exercised together.

using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using Xunit;

public class ProductsApiTests
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public ProductsApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetProduct_WithUnknownId_ReturnsNotFound()
    {
        // Arrange
        var unknownId = Guid.NewGuid();

        // Act
        var response = await _client.GetAsync($"/api/products/{unknownId}");

        // Assert
        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }
}

In a real project, use a separate connection string, test database, or controlled DbContext configuration for the test environment. Integration tests must never accidentally connect to a production database. Tests should also be independent from one another: each test should prepare its own required data or use a carefully controlled fixture.

Design principles for architectural testability

  • Receive dependencies explicitly through constructors.
  • Make the Application layer depend on abstractions rather than concrete Infrastructure classes.
  • Do not use repositories or DbContext directly inside controllers.
  • Limit static global state and direct use of DateTime.Now; introduce a clock abstraction when time affects business behavior.
  • Keep real SQL Server access out of unit tests.
  • Prepare a small, meaningful Arrange section for each test.
  • Use names that describe both the scenario and expected result.

Common mistakes

  1. Mocking everything: Mocking domain entities prevents the real business rules from being tested. Create real domain objects instead.
  2. Testing implementation details: Testing private methods or the exact form of a LINQ expression makes refactoring unnecessarily difficult. Test externally observable behavior.
  3. Using a database in unit tests: This makes tests slower and more fragile. Write separate integration tests for database behavior.
  4. Testing too many behaviors in one test: When the test fails, it becomes difficult to identify the broken behavior. Split scenarios into focused tests.
  5. Treating coverage as the only goal: High coverage does not automatically mean high-quality tests. Focus on meaningful verification of critical rules and failure paths.

Practice exercise

Task: Write tests for the product creation use case in the project:

  1. Verify that a valid request causes a new product to be added through the repository.
  2. Verify that a request containing a negative price produces a domain error.
  3. Verify that a successful API request returns 201 Created.
  4. Verify with an integration test that an unauthenticated request is rejected by the authentication or authorization pipeline.

Run the tests individually first, then run the entire solution with dotnet test. Test names should make it clear which behavior has failed when a test breaks.

Conclusion

In this lesson, we learned how to validate Clean Architecture layers with automated tests. Domain tests verify business rules in isolation. Application tests use mocked repositories to validate use case workflows. Controller tests verify HTTP result mapping, while integration tests exercise the real application pipeline.

Dependency Injection and abstractions are critical not only for code organization but also for testability. Good tests focus on externally observable behavior rather than implementation details. In the next stage, these tests can be included in a continuous integration pipeline so that every change is automatically validated.

Sources