Lesson 74 of 93 · 5 min read · Updated

Architecture Tests with NetArchTest: Making Dependency Rules Executable

Architecture decisions are usually written in a wiki page or a diagram, and over time the code drifts away from them. A developer in a hurry references an infrastructure class from the domain, the build passes, and nobody notices until the layers are tangled. Architecture tests turn those decisions into unit tests. This lesson uses NetArchTest to enforce nine rules on a layered project, so a violation fails the build the moment it is introduced instead of waiting for a code review.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. NetArchTest.Rules 1.3.2

The Rules to Enforce

The basic rule of an Onion or Clean architecture is that dependencies flow inward: Infrastructure depends on Application, Application depends on Domain, and Domain depends on nothing. The sample adds rules about naming and placement. In total the test class enforces nine rules:

  1. Domain has no dependency on Application.
  2. Domain has no dependency on Infrastructure.
  3. Application has no dependency on Infrastructure.
  4. Domain has no dependency on EF Core or ASP.NET Core.
  5. Domain events are sealed.
  6. Everything in Application/Ports is an interface.
  7. Domain has no dependency on the CQRS infrastructure or on DI.
  8. The generic CQRS infrastructure (Application/Cqrs) has no dependency on UseCases.
  9. Classes whose names end with Handler live in Application/UseCases.

The Shape of a NetArchTest Rule

Every rule follows the same pattern: select types, filter them, state a condition, get the result.

M08.LayeredDdd.Tests/Architecture/ArchitectureTests.cs

public class ArchitectureTests
{
private static readonly Assembly ProductionAssembly = typeof(Order).Assembly;

private const string DomainNamespace = "M08.LayeredDdd.Domain";
private const string ApplicationNamespace = "M08.LayeredDdd.Application";
private const string InfrastructureNamespace = "M08.LayeredDdd.Infrastructure";

[Fact]
public void Domain_ShouldNotDependOnInfrastructure()
{
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace(DomainNamespace)
.ShouldNot().HaveDependencyOn(InfrastructureNamespace)
.GetResult();

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

Types.InAssembly loads every type in the production assembly. That().ResideInNamespace(...) keeps the types in a namespace, including its child namespaces such as Domain.Entities. ShouldNot().HaveDependencyOn(...) is the condition. GetResult() returns a result with IsSuccessful and the names of the failing types.

The assertion passes those names into the FluentAssertions reason message ("types that break the rule: {0}"). When the rule fails, the output lists the exact classes to fix. FailingTypeNames can be null when the rule passes, so the ?? [] keeps string.Join safe.

The sample uses one assembly with namespaces as layers. In a solution with separate projects per layer, the same tests work with Types.InAssembly pointed at each layer's assembly.

Keeping Frameworks Out of the Domain

The domain should stay free of technology. Two rules check this with HaveDependencyOnAny, which accepts several namespaces:

M08.LayeredDdd.Tests/Architecture/ArchitectureTests.cs

[Fact]
public void Domain_ShouldNotDependOnEntityFrameworkOrAspNetCore()
{
// The domain model must stay technology independent.
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace(DomainNamespace)
.ShouldNot().HaveDependencyOnAny("Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore")
.GetResult();

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

[Fact]
public void Domain_ShouldNotDependOnCqrsOrDependencyInjection()
{
// Command/handler/pipeline infrastructure is an APPLICATION concern; the domain model must NOT know it.
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace(DomainNamespace)
.ShouldNot().HaveDependencyOnAny($"{ApplicationNamespace}.Cqrs", "Microsoft.Extensions.DependencyInjection")
.GetResult();

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

The EF Core rule is useful even though the sample does not reference EF Core today. It documents the decision and protects it the day someone adds an [Owned] attribute or a DbContext call to an entity.

Rules About Direction Inside a Layer

Layers are not the only boundaries. Inside Application, the generic dispatcher and behaviors must not know about specific use cases. The dependency must point from UseCases to Cqrs, never back:

M08.LayeredDdd.Tests/Architecture/ArchitectureTests.cs

[Fact]
public void CqrsInfrastructure_ShouldNotKnowConcreteUseCases()
{
// The generic infrastructure (dispatcher, behavior) does NOT know specific use cases;
// the dependency goes the other way: UseCases -> Cqrs.
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace($"{ApplicationNamespace}.Cqrs")
.ShouldNot().HaveDependencyOn($"{ApplicationNamespace}.UseCases")
.GetResult();

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

If someone added a special case for PlaceOrderCommand inside ValidationBehavior, this test would fail. The behavior would no longer be generic, and every new command would need another special case.

Rules About Shape and Placement

Some rules check what types look like or where they live:

M08.LayeredDdd.Tests/Architecture/ArchitectureTests.cs

[Fact]
public void CommandHandlers_ShouldResideInUseCases()
{
// No guessing needed to find a handler: they are all in one place.
var result = Types.InAssembly(ProductionAssembly)
.That().HaveNameEndingWith("Handler")
.And().AreClasses()
.Should().ResideInNamespace($"{ApplicationNamespace}.UseCases")
.GetResult();

result.IsSuccessful.Should().BeTrue(
"yanlış yerdeki handler'lar: {0}",
string.Join(", ", result.FailingTypeNames ?? []));
}

[Fact]
public void DomainEvents_ShouldBeSealed()
{
// Domain events describe a fact that happened in the past; they must not be extended by inheritance.
var result = Types.InAssembly(ProductionAssembly)
.That().ResideInNamespace($"{DomainNamespace}.Events")
.And().AreClasses()
.Should().BeSealed()
.GetResult();

result.IsSuccessful.Should().BeTrue(
"sealed olmayan olaylar: {0}",
string.Join(", ", result.FailingTypeNames ?? []));
}

The reason messages read "handlers in the wrong place: {0}" and "events that are not sealed: {0}". The remaining test, ApplicationPorts_ShouldBeInterfaces, uses Should().BeInterfaces() on the Ports namespace, so a concrete adapter cannot slip in next to the contracts.

Seeing a Rule Fail

To see the protection work, make Order use an Infrastructure type, for example by adding a field of type InMemoryOrderRepository, and run the tests. Domain_ShouldNotDependOnInfrastructure fails and names Order in its message.

Two pitfalls are worth knowing. First, NetArchTest reads the compiled code, so an unused using directive does not count as a dependency; only real use of a type does. Second, a rule passes when no types match the filter. A typo in a namespace constant makes every rule pass without checking anything. Keeping the namespaces in constants, as the sample does, reduces that risk; a quick check is to break a rule on purpose once and confirm the test fails.

Summary

  1. Architecture tests turn dependency rules from documentation into tests that fail the build.
  2. A NetArchTest rule selects types, filters them, states a condition and returns a result with the failing type names.
  3. Put the failing type names in the assertion message so a failure points to the class to fix.
  4. Enforce direction between layers, inside layers, and rules about type shape and placement.
  5. NetArchTest sees real type usage, not using directives, and a rule with no matching types passes, so break each rule once to confirm it works.