# Architecture tests that keep module boundaries real

Verified 2026-09 against <https://github.com/BenMorris/NetArchTest> (package `NetArchTest.Rules`),
<https://github.com/TNG/ArchUnitNET> (package `TngTech.ArchUnitNET.xUnitV3`) and
<https://learn.microsoft.com/en-us/ef/core/modeling/>.

These tests live in a normal test project and run in the ordinary test step. They are cheap
(reflection over already-built assemblies) and they fail the build on the day someone adds the
reference, rather than at the architecture review six months later.

## 1. Module depends only on another module's contracts

```csharp
using NetArchTest.Rules;
using Xunit;

public class ModuleBoundaryTests
{
    [Fact]
    public void Orders_does_not_reference_Billing_internals()
    {
        var result = Types.InAssembly(typeof(OrdersModule).Assembly)
            .That().ResideInNamespace("Acme.Modules.Orders")
            .ShouldNot().HaveDependencyOn("Acme.Modules.Billing")   // Billing.Contracts is a different namespace
            .GetResult();

        Assert.True(result.IsSuccessful, Describe(result));
    }

    private static string Describe(TestResult result) =>
        result.IsSuccessful
            ? string.Empty
            : "Offending types: " + string.Join(", ", result.FailingTypeNames ?? []);
}
```

Namespaces have to be chosen so the rule is expressible: `Acme.Modules.Billing.Contracts` must not be
nested under a namespace the rule forbids, or place contracts under `Acme.Contracts.Billing`. Decide
this when you create the second module, not when you write the test.

The `Describe` helper matters more than it looks: a bare `Assert.True(result.IsSuccessful)` tells the
next developer that "something" broke, which is how these tests end up `[Skip]`-ed.

## 2. The domain stays free of infrastructure

```csharp
[Fact]
public void Domain_does_not_depend_on_EfCore_or_AspNetCore()
{
    var result = Types.InAssembly(typeof(Order).Assembly)
        .That().ResideInNamespace("Acme.Modules.Orders.Domain")
        .ShouldNot().HaveDependencyOnAny("Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore")
        .GetResult();

    Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
}
```

This is the rule that actually decays. `[Required]`, `JsonPropertyName` and a `DbContext` reference
"just for this one query" arrive one at a time.

## 3. Implementation types stay internal

```csharp
[Fact]
public void Only_contracts_are_public()
{
    var result = Types.InAssembly(typeof(OrdersModule).Assembly)
        .That().ResideInNamespace("Acme.Modules.Orders")
        .And().DoNotResideInNamespace("Acme.Modules.Orders.Public")
        .And().AreNotStatic()                       // module registration extensions stay public
        .ShouldNot().BePublic()
        .GetResult();

    Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
}
```

Give the test project access with `<InternalsVisibleTo Include="Acme.Modules.Orders.Tests" />` in the
module's `.csproj` rather than making types public "so tests can see them".

## 4. No cross-schema foreign key (EF model test)

Architecture-test libraries see assemblies; this one has to look at the EF model, so it is a plain
xUnit test over the built `IModel`.

```csharp
using Microsoft.EntityFrameworkCore;
using Xunit;

[Fact]
public void Orders_has_no_foreign_key_into_another_schema()
{
    using var db = new OrdersDbContext(
        new DbContextOptionsBuilder<OrdersDbContext>().UseNpgsql("Host=localhost").Options);

    var offenders = db.Model.GetEntityTypes()
        .SelectMany(e => e.GetForeignKeys())
        .Where(fk => fk.PrincipalEntityType.GetSchema() != fk.DeclaringEntityType.GetSchema())
        .Select(fk => $"{fk.DeclaringEntityType.Name} -> {fk.PrincipalEntityType.Name}")
        .ToList();

    Assert.Empty(offenders);
}
```

No database is contacted — `UseNpgsql` with a connection string only builds the model. The same walk
over `db.Model.GetEntityTypes()` is the place to assert the other rule worth enforcing in a
multi-tenant service: every entity that declares a `TenantId` property must also have a global query
filter configured (see `multi-tenancy.md`).

## 5. ArchUnitNET when the rules get conditional

NetArchTest covers dependency rules. ArchUnitNET (package `TngTech.ArchUnitNET.xUnitV3` for xUnit v3)
is worth the extra setup when rules become conditional — "types named `*Handler` must be `sealed`,
`internal`, and live in the same namespace as their request".

```csharp
using ArchUnitNET.Domain;
using ArchUnitNET.Loader;
using ArchUnitNET.Fluent;
using static ArchUnitNET.Fluent.ArchRuleDefinition;

private static readonly Architecture Architecture =
    new ArchLoader().LoadAssemblies(typeof(OrdersModule).Assembly).Build();

[Fact]
public void Handlers_are_sealed()
{
    Classes().That().HaveNameEndingWith("Handler")
        .Should().BeSealed()
        .Check(Architecture);
}
```

Pick one library per solution. Two of them means two half-maintained rule sets.

## 6. Wiring into CI

Keep these in a dedicated `Architecture.Tests` project so they can be filtered in and out:

```bash
dotnet test tests/Architecture.Tests --logger "trx;LogFileName=architecture.trx"
```

Run them in the same job as the unit tests, not in a nightly. A boundary violation caught the next
morning has already been built on. If a rule must be broken deliberately, delete or amend the rule in
the same pull request — never `[Fact(Skip = "temporary")]`, which is permanent in practice.
