Quality & GrowthComplete guide

Architecture Testing

Architecture tests verify that structural rules — which layers may reference which, how types must be named, what may not depend on what — are enforced automatically rather than relying on code review alone.

Overview

Architecture rules decay when they exist only in diagrams and review comments. An architectural fitness function turns an important structural property into executable evidence: domain code has no outward dependency, application code owns ports, modules expose only intended contracts, handlers follow conventions, and adapters remain replaceable. Reflection libraries such as NetArchTest or ArchUnitNET inspect compiled assemblies; Roslyn analyzers provide earlier compiler and IDE feedback; project references and visibility enforce some rules before tests run. Good rules protect consequential boundaries rather than cosmetic preferences, name the violating types, and remain fast enough for every pull request. Existing systems need an explicit baseline and a ratchet that prevents new violations while teams remove old ones incrementally. Rules must evolve with architecture decisions, package or namespace moves, generated code, dynamic loading, and deployment topology, and they complement—not replace—behavior tests and design review.

What you will learn

  • Translate architecture decisions into executable rules.
  • Enforce inward project dependency direction.
  • Protect module contracts and visibility.
  • Choose reflection tests or analyzers.
  • Introduce a legacy baseline safely.
  • Keep diagnostics actionable and rules maintainable.

Prerequisites

  • Assemblies, project references, namespaces, and accessibility.
  • A documented target architecture and module ownership model.
  • A standard unit-test and CI pipeline.

When to use Architecture Testing

Good fit

  • A boundary is important and mechanically observable.
  • Multiple contributors can accidentally introduce coupling.
  • A legacy boundary needs a no-new-violations ratchet.

Choose another approach when

  • Rules encode taste with no design consequence.
  • A rule duplicates a compiler guarantee.
  • Tests replace design review or runtime behavior evidence.

Key concepts

Fitness functions

Automated checks continuously evaluate a measurable architectural property.

Dependency direction

Inner domain and application assemblies must not reference outer infrastructure or delivery assemblies.

Module boundaries

Only explicit public contracts may cross business-module ownership lines.

Naming and shape

Handlers, ports, adapters, and endpoints can follow searchable conventions when those conventions improve design.

Visibility

Internal types and friend assemblies reduce the surface that other modules can couple to.

Reflection tests

Compiled-assembly inspection is easy to add and works in an ordinary test runner.

Roslyn analyzers

Compiler-integrated rules give immediate feedback and can block builds before test execution.

Baselines and ratchets

Legacy violations are recorded while new violations fail and the permitted set only shrinks.

Architecture

Architecture tests run alongside unit and integration tests in CI; they inspect compiled assemblies and fail the build when a structural rule is violated, before code reaches main.

Compiled assemblies
NetArchTest rules
CI quality gate
Pull request feedback

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The sample compiles Domain, Application, Infrastructure, and Host separately, then uses reflection fitness functions to prove reference direction, port naming, adapter visibility, and composition behavior.

  1. 01
    Record the decision

    State the boundary, rationale, owner, and permitted dependency direction.

  2. 02
    Choose enforcement

    Use project structure, visibility, reflection tests, analyzers, or a combination.

  3. 03
    Load target assemblies

    Anchor rules on known types so renames and missing assemblies fail visibly.

  4. 04
    Express one rule

    Write a sentence-named test for each consequential property.

  5. 05
    Report violations

    List every offending type or reference in the failure output.

  6. 06
    Baseline legacy debt

    Capture existing exceptions with an owner and shrink-only removal plan.

  7. 07
    Run and evolve

    Execute on every pull request and update rules with approved architecture decisions.

Code example

Three focused tests enforce Clean Architecture dependency direction, naming conventions, and module isolation — all failing at CI rather than in a code review comment.

ArchitectureTests.cs
using NetArchTest.Rules;

public sealed class ArchitectureTests
{
    private const string DomainNamespace      = "Orders.Domain";
    private const string ApplicationNamespace = "Orders.Application";
    private const string InfraNamespace       = "Orders.Infrastructure";
    private const string WebNamespace         = "Orders.Web";

    [Fact]
    public void Domain_must_not_reference_application_or_outer_layers()
    {
        var result = Types.InAssembly(typeof(Orders.Domain.Order).Assembly)
            .Should()
            .NotHaveDependencyOnAny(
                ApplicationNamespace,
                InfraNamespace,
                WebNamespace)
            .GetResult();

        Assert.True(result.IsSuccessful,
            "Domain layer has forbidden outward dependency:\n" +
            string.Join("\n", result.FailingTypeNames ?? []));
    }

    [Fact]
    public void Application_must_not_reference_infrastructure_or_web()
    {
        var result = Types.InAssembly(typeof(Orders.Application.PlaceOrderCommand).Assembly)
            .Should()
            .NotHaveDependencyOnAny(InfraNamespace, WebNamespace)
            .GetResult();

        Assert.True(result.IsSuccessful,
            "Application layer has forbidden outward dependency:\n" +
            string.Join("\n", result.FailingTypeNames ?? []));
    }

    [Fact]
    public void Repositories_must_implement_IRepository_and_live_in_infrastructure()
    {
        var result = Types.InCurrentDomain()
            .That().ImplementInterface(typeof(IRepository<>))
            .Should()
            .ResideInNamespace(InfraNamespace)
            .GetResult();

        Assert.True(result.IsSuccessful,
            "Repository implementation found outside Infrastructure:\n" +
            string.Join("\n", result.FailingTypeNames ?? []));
    }
}

Testing strategy

Prove each fitness function can detect a representative forbidden dependency or shape.

  • Use fixture assemblies with deliberate violations.
  • Fail when a target assembly is missing.
  • Assert every violating type is reported.
  • Test generated-code exclusions narrowly.
  • Verify baseline entries cannot grow silently.
  • Run rules against Release assemblies in CI.

Security considerations

Structural rules can enforce security boundaries before runtime.

  • Keep secret providers out of domain code.
  • Restrict unsafe APIs to approved adapters.
  • Protect authorization policy ownership.
  • Prevent UI modules from referencing persistence.
  • Review exclusions as security changes.

Performance and scalability

Rules should be cheap enough for every change.

  • Load each assembly once.
  • Cache type scans within a test run.
  • Prefer project references for coarse boundaries.
  • Split expensive repository-wide analysis.
  • Track architecture-test duration.

Deployment and operations

Run architecture evidence before packaging so invalid structure never becomes an artifact.

  • Build Release assemblies first.
  • Run on every pull request.
  • Publish violation reports.
  • Block merges on new violations.
  • Review baselines during modernization.

Common problems and fixes

Rule finds no types.

Likely cause: The namespace or assembly anchor moved.

Fix: Fail on an empty selection and anchor with a known type.

Valid generated code fails.

Likely cause: The rule scans compiler output indiscriminately.

Fix: Exclude a narrow generated-code marker with rationale.

Many legacy violations block adoption.

Likely cause: The target rule was enabled without a baseline.

Fix: Record current debt and enforce no new violations.

Tests pass despite a project reference.

Likely cause: Only type usage was inspected.

Fix: Assert assembly references or project graph directly.

Failures are hard to fix.

Likely cause: The assertion reports only false.

Fix: Print violating types and the governing decision.

Rules fight approved design.

Likely cause: Architecture changed but evidence did not.

Fix: Update the ADR and fitness function in the same change.

Best practices

  • Protect consequential boundaries.
  • Prefer compile-time enforcement first.
  • Name rules as sentences.
  • Report violating types.
  • Fail on empty scans.
  • Baseline legacy debt explicitly.
  • Keep exceptions narrow and owned.
  • Update rules with ADRs.

Production checklist

  • Important boundaries have recorded decisions.
  • Project references point inward.
  • Module contracts are explicit.
  • Rules fail on empty selections.
  • Violations list concrete types.
  • Legacy baselines cannot grow.
  • CI blocks new violations.
  • Rules evolve with approved decisions.

Common interview questions

What is an architectural fitness function?

An automated check that continuously evaluates a structural or operational architecture property.

Reflection test versus Roslyn analyzer?

Reflection inspects compiled assemblies in a test runner; an analyzer reports during compilation and in the IDE.

How do project references help?

They make coarse dependency direction a compiler-enforced graph rather than a naming convention.

How do you adopt rules in legacy code?

Record existing violations, fail only on growth, and shrink the baseline through owned increments.

Why fail on an empty type selection?

Otherwise a rename can make a rule silently test nothing while remaining green.

Should every naming convention be tested?

No; enforce conventions only when they protect ownership, discovery, safety, or replaceability.

Do architecture tests replace review?

No; they automate observable invariants while review handles tradeoffs and concepts the code graph cannot express.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Architecture Boundary Lab

A multi-project .NET 10 sample enforcing inward dependencies, port naming, adapter visibility, and composition with executable reflection fitness functions.

.NET 10Architecture TestingReflectionxUnit
dedicated-samplefitness-functionsdependency-rulemodule-boundary
Run
dotnet run --project src/ArchitectureBoundaryLab
Test
dotnet test ArchitectureBoundaryLab.slnx