Lesson 65 of 93 · 6 min read · Updated

Testing in Layered Architectures: Architecture Changes Boundaries, Not Principles

When a project moves from a single class library to an Onion, Clean or Hexagonal layout, many teams assume they need a new way of testing. They do not. The rules stay the same: test behavior, keep tests fast and isolated, and replace only what you do not control. What changes is where the boundaries are, and therefore where each kind of test starts and stops. This lesson introduces the layered sample project used in the rest of this section and shows how its boundaries shape the tests.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2 (the last version under the Apache 2.0 licence; 8.x is commercial)
  4. Moq 4.21.0
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0
  6. Microsoft.Extensions.DependencyInjection 11.0.0
  7. NetArchTest.Rules 1.3.2

The Layer Layout

The sample is a small order system. It uses one production project and represents the Onion layers with folders and namespaces. Each layer has one job, and dependencies only point inward.

M08.LayeredDdd/
Domain/ <- business decisions. Depends on NOTHING.
ValueObjects/ Money, CustomerId, OrderId
Entities/ Order (aggregate root)
Events/ OrderPlaced, OrderCancelled
Services/ ShippingDiscountService
Application/ <- use cases. Depends only on Domain.
Cqrs/ ICommand, ICommandHandler, ICommandPipelineBehavior, CommandDispatcher, ValidationBehavior
Ports/ IOrderRepository, ICustomerDirectory, IDomainEventPublisher
UseCases/ PlaceOrderHandler, PlaceOrderCommandValidator
ApplicationServiceRegistration.cs <- AddApplication() DI registrations
Infrastructure/ <- technology adapters. Knows Application.

The project file explains the choice. In a real system each layer would be a separate project, and the compiler would stop a wrong reference. In a single project the compiler cannot do that, so the rule is enforced with architecture tests instead.

M08.LayeredDdd/M08.LayeredDdd.csproj

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<!--
In this single project we represent the Onion layers with FOLDER + NAMESPACE:
Domain -> business decisions (depends on nothing)
Application -> use cases (depends only on Domain)
Infrastructure -> technology adapters (implements the Application ports)

In a real project these are SEPARATE PROJECTS and the compiler enforces
the dependency direction. Here we enforce the same rule with ARCHITECTURE TESTS (NetArchTest).
-->
</PropertyGroup>

<!-- IServiceCollection (Application/ApplicationServiceRegistration) is part of the framework
starting with .NET 11; no separate package is needed (NU1510).
The CQRS infrastructure is hand-written; MediatR is deliberately NOT used (13.x+ has a commercial licence). -->

</Project>

Ports Point Inward, Adapters Live Outside

The Application layer needs to save orders, ask whether a customer is loyal and publish events. It does not know how those things happen. It declares what it needs as interfaces, called ports.

M08.LayeredDdd/Application/Ports/Ports.cs

/// <summary>
/// PORT: a capability the Application layer needs.
/// Its implementation (adapter) lives in the Infrastructure layer: the dependency flows INWARD.
/// </summary>
public interface IOrderRepository
{
Task<Order?> GetAsync(OrderId id, CancellationToken cancellationToken = default);

Task SaveAsync(Order order, CancellationToken cancellationToken = default);
}

/// <summary>Customer information port.</summary>
public interface ICustomerDirectory
{
Task<bool> IsLoyalAsync(CustomerId customerId, CancellationToken cancellationToken = default);
}

/// <summary>Port that publishes domain events to the outside world.</summary>
public interface IDomainEventPublisher
{
Task PublishAsync(IReadOnlyList<IDomainEvent> events, CancellationToken cancellationToken = default);
}

The Infrastructure layer implements these ports. In the sample the adapters keep data in memory, which also makes them useful as lightweight fakes in tests.

M08.LayeredDdd/Infrastructure/InMemoryOrderRepository.cs

/// <summary>
/// ADAPTER: implements an Application port with a concrete technology.
/// The dependency direction is INWARD: Infrastructure knows Application;
/// Application does NOT know Infrastructure. We will enforce this with an architecture test.
/// </summary>
public sealed class InMemoryOrderRepository : IOrderRepository
{
private readonly ConcurrentDictionary<OrderId, Order> _orders = new();

public Task<Order?> GetAsync(OrderId id, CancellationToken cancellationToken = default) =>
Task.FromResult(_orders.GetValueOrDefault(id));

public Task SaveAsync(Order order, CancellationToken cancellationToken = default)
{
_orders[order.Id] = order;
return Task.CompletedTask;
}
}

/// <summary>Adapter that collects events in memory (for tests/development).</summary>
public sealed class InMemoryDomainEventPublisher : IDomainEventPublisher
{
private readonly List<IDomainEvent> _published = [];

public IReadOnlyList<IDomainEvent> Published => _published;

public Task PublishAsync(IReadOnlyList<IDomainEvent> events, CancellationToken cancellationToken = default)
{
_published.AddRange(events);
return Task.CompletedTask;
}
}

What the Boundaries Mean for Tests

Each boundary in the layout is also a natural place to start or stop a test. The principles do not move, but the scope of each test follows the layers:

LayerWhat the tests checkWhat they need
DomainBusiness decisions: rules, state transitions, invariants, eventsPlain C#. No mocks, no container, no database
ApplicationUse cases: orchestration, policies, port interactions, error pathsFakes or mocks for the ports, a fake clock
Application + containerDI registrations and the command pipelineA real ServiceCollection
Whole assemblyDependency rules between layersNetArchTest

Because the Domain layer depends on nothing, its tests are the cheapest to write and the fastest to run. Because the Application layer talks to the outside world only through ports, its tests can swap each port for an in-memory adapter or a mock without changing production code. Infrastructure adapters, the parts that touch real databases and queues, belong to integration tests and are out of scope for this section.

Enforcing the Direction

A layering rule that lives only in a wiki page will be broken sooner or later. Somebody adds a using for an Infrastructure type inside a use case, the build passes, and the layers start to blur. An architecture test turns the rule into something that fails the build.

M08.LayeredDdd.Tests/Architecture/ArchitectureTests.cs

[Fact]
public void Application_ShouldNotDependOnInfrastructure()
{
// Use cases depend on PORTS, not on ADAPTERS.
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace(ApplicationNamespace)
.ShouldNot().HaveDependencyOn(InfrastructureNamespace)
.GetResult();

result.IsSuccessful.Should().BeTrue(
"kural ihlali yapan tipler: {0}",
string.Join(", ", result.FailingTypeNames ?? []));
}

The reason message lists the types that broke the rule, so a failure tells you exactly which file to fix. Architecture tests get their own lesson at the end of this section.

A common mistake is to treat the layer structure as a reason to mock everything at every boundary. The boundaries tell you where tests can start and stop. They do not tell you to replace the domain model with mocks in application tests. The real Order aggregate is used in every application test in this section, because it is fast, deterministic and part of the behavior being tested.

Summary

  1. Layered architectures do not change testing principles; they change where test boundaries sit.
  2. The Domain layer depends on nothing, so domain tests are plain C# with no mocks.
  3. The Application layer reaches the outside world only through ports, so its tests replace ports with in-memory adapters or mocks.
  4. When layers share one project, architecture tests enforce the dependency direction that separate projects would enforce at compile time.
  5. Do not mock the domain model in application tests; use the real aggregate.