Skip to content

Architecture tests

This page sets the rules for architecture tests: tests that check layering, dependencies, naming and type shape by reflection. It is written for engineers who add or change an *.ArchitectureTests project and for those who maintain the templates that ship one. Following it means an architecture rule that passes has actually looked at the code it is about.

How to write NetArchTest rules is explained in Architecture tests in ConnectSoft Microservice Template. Project naming and the Architecture Unit Tests category follow CS-TST-004.

What the templates ship

ConnectSoft.BaseTemplate ships an ArchitectureTests project with 13 test classes and 58 tests. Services generated from it inherit them. The rules cover:

  • Layering: lower layers do not reference upper layers; controllers and gRPC services do not reference the persistence model or domain service implementations.
  • Model isolation: the entity model does not reference infrastructure, persistence, messaging or service models; the application and domain models do not reference concrete persistence implementations.
  • Patterns: domain services, use cases, repositories, specifications, domain events, commands and messages implement the expected interfaces and live in the expected projects.
  • Naming: interfaces start with I; commands, events, use cases, inputs, outputs, options, repositories, specifications, extension containers and exceptions end with the matching suffix.
  • Options: options classes are public sealed classes with public properties and data annotations.

Rules

CS-TST-024: Write architecture tests with NetArchTest

Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active

Why

Every ConnectSoft architecture test project uses NetArchTest.Rules, and no repository uses another library. One library keeps the rules readable across repositories and lets template rules move into services without translation.

Do

  • Reference NetArchTest.Rules from the architecture test project, with its version in Directory.Packages.props.
  • Put architecture tests in a project named <Repository>.ArchitectureTests.

Don't

  • Add ArchUnitNET or another architecture testing library.
  • Put architecture rules in a unit test project.

How to check

The architecture test project references NetArchTest.Rules and no other architecture testing package.

CS-TST-025: Scan an explicit set of assemblies that covers the shipped ones

Severity: blocker · Applies to: service, library, template · Enforced by: manual (target: ENF-057) · Status: active

Why

Types.InCurrentDomain() and AppDomain.CurrentDomain.GetAssemblies() return only the assemblies already loaded into the test process. .NET loads assemblies when code first uses them, and a project reference does not load anything. A rule that filters on a namespace in an assembly no earlier test touched passes over an empty set. In one measured suite, 8 of 19 shipped assemblies were never loaded, and two rules passed while the code broke them dozens of times.

Do

  • In a new architecture test suite, load the assemblies under test explicitly, through a marker type of each one (typeof(OrderService).Assembly) or by name from the test output folder.
  • Add a test that compares the scanned set with the shipped set, for example every <Repository>*.dll in the output folder, and fails when an assembly is missing from the scan.
  • Pass the explicit set to Types.InAssemblies(...).

Don't

  • Use Types.InCurrentDomain() or AppDomain.CurrentDomain.GetAssemblies() in a new suite.

Existing suites that scan loaded assemblies stay as they are until the template is fixed. Completing the scan can turn rules red where the rule, not the code, is wrong, so each such rule needs a review first. That work is tracked in ENF-057; do not change an existing suite's discovery on your own.

Example

internal static class ArchitectureSubjects
{
    /// <summary>The assemblies that the architecture rules check.</summary>
    internal static readonly IReadOnlyList<Assembly> Assemblies =
    [
        typeof(Order).Assembly,                 // EntityModel
        typeof(IOrderRepository).Assembly,      // PersistenceModel
        typeof(OrderService).Assembly,          // DomainModel.Impl
        typeof(OrdersController).Assembly,      // ServiceModel.RestApi
    ];
}

[TestMethod]
public void ScannedAssembliesShouldCoverShippedAssemblies()
{
    // Arrange
    string outputFolder = AppContext.BaseDirectory;
    IEnumerable<string> shipped = Directory.GetFiles(outputFolder, "OrderService*.dll")
        .Select(file => Path.GetFileNameWithoutExtension(file))
        .Where(name => !name.EndsWith("Tests", StringComparison.Ordinal));

    // Act
    IEnumerable<string> scanned = ArchitectureSubjects.Assemblies.Select(assembly => assembly.GetName().Name!);

    // Assert
    CollectionAssert.IsSubsetOf(shipped.ToList(), scanned.ToList());
}

How to check

  • New architecture test files do not call Types.InCurrentDomain() or AppDomain.CurrentDomain.GetAssemblies().
  • The suite has a coverage test that compares scanned and shipped assemblies.

CS-TST-026: Assert that every rule has something to check

Severity: major · Applies to: service, library, template · Enforced by: manual (target: ENF-057, ENF-058) · Status: active

Why

A NetArchTest rule over an empty set of types is successful. A namespace typo, a renamed project or an assembly that was not scanned turns the rule into a test that cannot fail, and nothing in the result says so.

Do

  • Before you assert a rule, assert that the selected types are not empty, with a message that names the selection.
  • Select types by an assembly marker or a full namespace that exists, not by a fragment.

Don't

  • Assert a rule over a selection whose size you never check.
  • Write an assertion that cannot fail, such as Assert.IsGreaterThanOrEqualTo(0, count).

Example

// Arrange
PredicateList repositories = Types.InAssemblies(ArchitectureSubjects.Assemblies)
    .That().HaveNameEndingWith("Repository");
Assert.IsNotEmpty(repositories.GetTypes(), "No repository types were found to check.");

// Act
TestResult result = repositories.Should().ResideInNamespaceStartingWith("OrderService.PersistenceModel").GetResult();

// Assert
Assert.IsTrue(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));

How to check

Each new rule asserts that its type selection is not empty before it asserts the rule.

CS-TST-027: Keep one test per architecture rule

Severity: minor · Applies to: service, library, template · Enforced by: manual (target: ENF-057) · Status: active

Why

When the same rule is written in two test classes, the copies drift: one gets fixed and the other keeps the old rule, and a failure shows up twice with different messages. The base template has such copies, for example of the exception, command and event naming rules.

Do

  • Keep each rule in the class for its topic, such as naming rules in the naming conventions class.
  • Before you add a rule, search the project for a test with the same name or the same selection.

Don't

  • Copy a rule into a second class to group it with related rules.

How to check

Test method names are unique across the architecture test project.