DEV Community

Cover image for ArchUnitNET: Architecture Tests for .NET Azure Functions
Martin Oehlert
Martin Oehlert

Posted on AI-assisted

ArchUnitNET: Architecture Tests for .NET Azure Functions

Why did a queue-triggered Function that wrote invoices straight through a BlobContainerClient pass code review, and why did moving it behind the application layer cost a sprint? The compiler had no reason to object: the Azure Functions host project references the infrastructure project so Program.cs can register it, and that same reference lets every Function class skip the application layer. Reviewers see one constructor parameter in a diff, not the dependency graph. ArchUnitNET turns "Functions only call the application layer" into an xUnit v3 test that fails the build, and the first version of that test in this article was green while the violation was still in the code.

Testing .NET on Azure: Beyond Unit Tests (6-part series)

Parts 1 and 2 ran OrderPipelineDemo against Azurite and the Cosmos DB and Service Bus emulators, which tests what the code does. This part tests how the code is put together, so it needs no containers at all. The code is in the companion repo: the same order pipeline split into layers, on .NET 10 and xUnit v3, with ArchUnitNET 0.13.5 through its TngTech.ArchUnitNET.xUnitV3 package.

The Function that skipped a layer

This is OrderProcessor from Part 1. A paid order arrives on the orders queue and the Function writes an invoice to Blob Storage:

public sealed class OrderProcessor(BlobContainerClient invoices, ILogger<OrderProcessor> logger)
{
    [Function(nameof(OrderProcessor))]
    public async Task Run([QueueTrigger("orders")] Order order, CancellationToken cancellationToken)
    {
        if (order.Status != OrderStatus.Paid)
            return;

        await invoices.CreateIfNotExistsAsync(cancellationToken: cancellationToken);

        var invoice = new Invoice(order.Id, order.CustomerId, order.Total);
        await invoices.GetBlobClient($"order-{order.Id}.json")
            .UploadAsync(BinaryData.FromObjectAsJson(invoice), overwrite: true, cancellationToken);

        logger.LogInformation("Invoice written for order {OrderId}", order.Id);
    }
}
Enter fullscreen mode Exit fullscreen mode

It works, and Part 1 proved it against Azurite. The cost is in what the trigger method decides on its own. Only paid orders get an invoice. The blob is named order-{id}.json. overwrite: true means a retried message replaces the invoice instead of failing. The container gets created on every message. Those are rules about invoices, and they live in a method whose job is to take a message off a queue.

The refactor started when invoices had to go to a second place. Every one of those decisions had to be found, moved into a use case behind a port, covered by tests that no longer needed Azurite, and the DI registrations rewired. One Function is an afternoon. Every Function that took the same shortcut, each with its own naming and overwrite rules, turned that afternoon into a sprint.

Review didn't catch it because the change that introduced it was one constructor parameter. The compiler didn't catch it because the reference is legal. Microsoft's Clean Architecture guidance says the UI layer "ideally shouldn't know about the implementation types defined in the Infrastructure layer", and in the same breath that those types are "required for the app to execute". In a Function app the host project is the UI layer: Program.cs registers the infrastructure, so the host has to reference it, and every Function class in that project can use the reference too. Project references can keep Domain and Application clean. They can't say "this project may reference Infrastructure, but only from Program.cs".

Splitting the order pipeline into four projects

The layered sample splits the same pipeline into four projects:

  • OrderPipeline.Domain: Order, OrderStatus, Invoice. No package references.
  • OrderPipeline.Application: the IssueInvoice use case and the IInvoiceStore port it writes through.
  • OrderPipeline.Infrastructure: BlobInvoiceStore, the Blob Storage adapter, plus an AddInfrastructure extension for DI.
  • OrderPipeline.Functions: the isolated worker host with OrderProcessor and Program.cs.

Allowed and forbidden dependencies between the four OrderPipeline projects

The invoice rules from the trigger method now sit in the use case, and the only thing it knows about storage is the port:

public interface IInvoiceStore
{
    Task SaveAsync(Invoice invoice, CancellationToken cancellationToken);
}

public sealed class IssueInvoice(IInvoiceStore invoices)
{
    public async Task<Invoice?> HandleAsync(Order order, CancellationToken cancellationToken)
    {
        if (order.Status != OrderStatus.Paid)
            return null;

        var invoice = new Invoice(order.Id, order.CustomerId, order.Total);
        await invoices.SaveAsync(invoice, cancellationToken);
        return invoice;
    }
}
Enter fullscreen mode Exit fullscreen mode

The blob name, overwrite: true and CreateIfNotExistsAsync moved into BlobInvoiceStore, where they are storage details again. The Function shrinks to a trigger and one call:

public sealed class OrderProcessor(IssueInvoice issueInvoice, ILogger<OrderProcessor> logger)
{
    [Function(nameof(OrderProcessor))]
    public async Task Run([QueueTrigger("orders")] Order order, CancellationToken cancellationToken)
    {
        var invoice = await issueInvoice.HandleAsync(order, cancellationToken);

        if (invoice is not null)
            logger.LogInformation("Invoice written for order {OrderId}", order.Id);
    }
}
Enter fullscreen mode Exit fullscreen mode

The host project still needs both references, and that is the gap the two "rule 3" arrows in the diagram mark:

<ItemGroup>
  <ProjectReference Include="../OrderPipeline.Application/OrderPipeline.Application.csproj" />
  <!-- Only Program.cs may use this reference; OrderPipeline.ArchitectureTests enforces that -->
  <ProjectReference Include="../OrderPipeline.Infrastructure/OrderPipeline.Infrastructure.csproj" />
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

Nothing in that file stops the next pull request from injecting BlobInvoiceStore into OrderProcessor again. The rest of this article is the test that does.

Loading the architecture once

ArchUnitNET reads the compiled assemblies with Mono.Cecil and builds a model of every type and dependency in them. For xUnit v3 the package is TngTech.ArchUnitNET.xUnitV3; TngTech.ArchUnitNET.xUnit targets xUnit v2. The samples repo pins versions centrally:

<!-- Directory.Packages.props -->
<PackageVersion Include="TngTech.ArchUnitNET.xUnitV3" Version="0.13.5" />

<!-- OrderPipeline.ArchitectureTests.csproj -->
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="TngTech.ArchUnitNET.xUnitV3" />
<PackageReference Include="xunit.v3" />
Enter fullscreen mode Exit fullscreen mode

The package pulls in TngTech.ArchUnitNET 0.13.5 and adds one extension method that matters: rule.Check(architecture). It throws a FailedArchRuleException, an XunitException, whose message lists every violating type and every dependency it shouldn't have. The plain alternative, Assert.True(rule.HasNoViolations(architecture)), fails with Assert.True() Failure and leaves you to find the class yourself.

The test project references the Functions project, which brings the other three along. Loading means one typeof per layer:

public class LayerRulesTests
{
    private static readonly Architecture Architecture = new ArchLoader()
        .LoadAssemblies(
            typeof(Order).Assembly,
            typeof(IssueInvoice).Assembly,
            typeof(BlobInvoiceStore).Assembly,
            typeof(OrderProcessor).Assembly)
        .Build();

    private static readonly IObjectProvider<IType> Domain =
        Types().That().ResideInAssembly(typeof(Order).Assembly).As("Domain");

    private static readonly IObjectProvider<IType> Application =
        Types().That().ResideInAssembly(typeof(IssueInvoice).Assembly).As("Application");

    private static readonly IObjectProvider<IType> Infrastructure =
        Types().That().ResideInAssembly(typeof(BlobInvoiceStore).Assembly).As("Infrastructure");

    // The host assembly also holds Program.cs (the composition root, allowed to wire up Infrastructure)
    // and the types the Worker SDK generates; the rule is about the trigger classes.
    private static readonly IObjectProvider<IType> Functions =
        Classes().That().FollowCustomPredicate(DeclaresFunction, "declare [Function] methods").As("Functions");

    private static bool DeclaresFunction(Class type) =>
        type.Members.Any(member => member.HasAttribute(typeof(FunctionAttribute).FullName!));
}
Enter fullscreen mode Exit fullscreen mode

The static readonly field loads the model once per test class, and Build() caches it globally per set of assemblies, so a second test class loading the same four gets the cached instance. It is cheap either way: loading the Part 1 Functions assembly took 94 ms, and the whole architecture test project, seven tests, finishes in about a second.

Three of the layers are "everything in this assembly", because each layer is its own project. If your layers are folders in one project, select them by namespace with ResideInNamespaceOrBelow("OrderPipeline.Domain") (new in 0.13.5). Not ResideInNamespace: that one is an exact match, so OrderPipeline.Domain.Orders would fall outside the layer and outside every rule about it.

The Functions layer is narrower than its assembly on purpose. The host project also contains Program.cs, the composition root, which is allowed to touch Infrastructure, and six classes the Worker SDK generates. ArchUnitNET has no predicate for "a class that declares a method with this attribute", so FollowCustomPredicate does it with a lambda over the class members, matched on the full name of FunctionAttribute. That is the same definition the runtime uses: a function is a public method with [Function] on a public class. The second argument is the description ArchUnitNET prints when the rule fails, and .As("Functions") names the layer in the message. For rules about the methods themselves, MethodMembers().That().HaveAnyAttributes(typeof(FunctionAttribute)) selects them directly.

Three rules, one per arrow

Each red arrow in the diagram becomes one [Fact]:

// Types(true): the SDK assemblies are not loaded, so Types() would hold none of their types.
private static readonly IObjectProvider<IType> AzureSdk =
    Types(true).That().ResideInNamespaceOrBelow("Azure")
        .Or().ResideInNamespaceOrBelow("Microsoft.Azure")
        .As("Azure SDK types");

private static readonly IObjectProvider<IType> StorageClients =
    Types(true).That().ResideInNamespaceOrBelow(typeof(BlobContainerClient).Namespace!)
        .As("Blob Storage client types");

[Fact]
public void Domain_does_not_depend_on_the_Azure_SDK() =>
    Types().That().Are(Domain).Should().NotDependOnAny(AzureSdk).Check(Architecture);

[Fact]
public void Application_does_not_depend_on_Infrastructure() =>
    Types().That().Are(Application).Should().NotDependOnAny(Infrastructure).Check(Architecture);

[Fact]
public void Functions_do_not_depend_on_Infrastructure_or_storage_clients() =>
    Types().That().Are(Functions).Should()
        .NotDependOnAny(Infrastructure)
        .AndShould().NotDependOnAny(StorageClients)
        .Check(Architecture);
Enter fullscreen mode Exit fullscreen mode

The Domain rule can be broad: anything under Azure or Microsoft.Azure is out, whether it arrives as a package someone adds "just for the ETag type" or as an attribute from the Functions SDK.

The Application rule is the cheapest of the three today. Infrastructure references Application, so a reference back would be a project cycle that MSBuild refuses. It stays because layouts change: when the layers become folders in one project, the namespace version of this rule is the only thing left guarding the arrow.

The Functions rule can't be broad. A Function class needs Microsoft.Azure.Functions.Worker for [Function] and [QueueTrigger], and a Service Bus Function needs ServiceBusReceivedMessage from Azure.Messaging.ServiceBus. So it forbids two specific things: the Infrastructure layer, and the storage client namespace. That namespace comes from typeof(BlobContainerClient).Namespace, so a typo in it is a compile error instead of a rule that checks nothing (more on that in the next section). If your Functions also talk to Cosmos DB, add typeof(CosmosClient).Namespace the same way.

To see the rule work, put BlobInvoiceStore back into OrderProcessor's constructor and call it instead of the use case. dotnet test fails with:

failed OrderPipeline.ArchitectureTests.LayerRulesTests.Functions_do_not_depend_on_Infrastructure_or_storage_clients (140ms)
  ArchUnitNET.xUnitV3.FailedArchRuleException : "Types that are Functions should not depend on any Infrastructure and should not depend on any Blob Storage client types" failed:
    OrderPipeline.Functions.OrderProcessor does depend on "OrderPipeline.Infrastructure.BlobInvoiceStore"
Enter fullscreen mode Exit fullscreen mode

The rule's sentence is built from the .As(...) names, and the second line names the class and the type it shouldn't use. It's the review comment nobody wrote, and CI leaves it on the commit that adds the parameter.

Why the first rule was green

The first version of the Functions rule didn't use Types(true). Pointed at the Part 1 code, where OrderProcessor still takes a BlobContainerClient, it passed. The sample keeps both versions in FirstAttemptTests, loaded against OrderPipelineDemo:

[Fact]
public void Types_without_referenced_types_misses_the_blob_client()
{
    var rule = Types().That().HaveName("OrderProcessor").Should()
        .NotDependOnAny(Types().That().ResideInNamespaceOrBelow("Azure.Storage"));

    Assert.True(rule.HasNoViolations(Before));
}

[Fact]
public void Types_with_referenced_types_catches_the_blob_client()
{
    var rule = Types().That().HaveName("OrderProcessor").Should()
        .NotDependOnAny(Types(true).That().ResideInNamespaceOrBelow("Azure.Storage"));

    var failure = Assert.Throws<FailedArchRuleException>(() => rule.Check(Before));
    Assert.Contains("Azure.Storage.Blobs.BlobContainerClient", failure.Message, StringComparison.Ordinal);
}
Enter fullscreen mode Exit fullscreen mode

Types() returns the types declared in the loaded assemblies. The test loaded the Functions assembly, not Azure.Storage.Blobs.dll, so Types().That().ResideInNamespaceOrBelow("Azure.Storage") is an empty set. "Depends on nothing in an empty set" is true for every class, so the rule passes, with the violation sitting in the constructor. The signature is Types(bool includeReferenced = false), and Types(true) adds every type the loaded assemblies reference. With it, the same rule fails and names what it found:

"Types that have name "OrderProcessor" should not depend on any Types (including referenced) that reside in namespace with full name "Azure.Storage" or below" failed:
    OrderPipelineDemo.OrderProcessor does depend on "Azure.Storage.Blobs.BlobContainerClient" and "Azure.Storage.Blobs.BlobClient" and "Azure.Storage.Blobs.Models.BlobContainerInfo" and "Azure.Storage.Blobs.Models.BlobContentInfo"
Enter fullscreen mode Exit fullscreen mode

ArchUnitNET does guard one side of this. Since RequirePositiveResults defaults to true, a rule whose subject set is empty fails with "The rule requires positive evaluation, not just absence of violations", so a renamed Domain namespace can't switch rule 1 off. The set inside NotDependOnAny gets no such check: an empty forbidden set, from Types() or from a typo like "Azure.Storgae", passes silently. The sample closes that gap with one more test:

// NotDependOnAny passes on an empty set, so a typo in a namespace would turn a rule into a no-op.
[Fact]
public void Forbidden_sets_are_not_empty()
{
    Assert.NotEmpty(AzureSdk.GetObjects(Architecture));
    Assert.NotEmpty(StorageClients.GetObjects(Architecture));
    Assert.NotEmpty(Infrastructure.GetObjects(Architecture));
}
Enter fullscreen mode Exit fullscreen mode

I now break every new architecture rule once on purpose before I trust it. Until I've seen it go red, I don't know whether it checks anything.

The code the Functions SDK writes for you

The [Function] selection keeps generated code out of rule 3. It comes back as soon as a rule points the other way. Function classes are entry points: the host calls them, and nothing in your own code should. With one Function and no callers in the sample, this rule looks like it can't fail:

// DirectFunctionExecutor, generated by the Worker SDK, calls every Function class.
[Fact]
public void Nothing_but_generated_code_depends_on_Functions() =>
    Types().That().AreNot(Functions)
        .And().DoNotHaveAnyAttributes(typeof(GeneratedCodeAttribute))
        .Should().NotDependOnAny(Functions)
        .Check(Architecture);
Enter fullscreen mode Exit fullscreen mode

Without the DoNotHaveAnyAttributes line, it fails on the first run:

"Types that are not Functions should not depend on any Functions" failed:
    OrderPipeline.Functions.DirectFunctionExecutor does depend on "OrderPipeline.Functions.OrderProcessor"
Enter fullscreen mode Exit fullscreen mode

DirectFunctionExecutor isn't in the project. The Worker SDK's source generators add it at build time, along with five more classes: GeneratedFunctionMetadataProvider, FunctionExecutorAutoStartup, FunctionExecutorHostBuilderExtensions, FunctionMetadataProviderAutoStartup and WorkerHostBuilderFunctionMetadataProviderExtension. The executor calls each Function class directly, so it depends on all of them. Part 1's OrderPipelineDemo gets a seventh, WorkerExtensionStartupCodeExecutor.

They land in the project's root namespace, OrderPipeline.Functions, next to OrderProcessor, so excluding them by namespace would exclude your Functions too. Excluding them by name works until an SDK update adds an eighth. What all seven share is [GeneratedCode] from System.CodeDom.Compiler, and Program doesn't carry it, so DoNotHaveAnyAttributes(typeof(GeneratedCodeAttribute)) removes exactly the generated classes. Any rule whose subject is "every type in the host assembly" needs the same line.

Architecture tests as a CI gate

The architecture tests get their own workflow in the samples repo, next to the container workflow from Parts 1 and 2:

name: OrderPipelineLayered architecture tests

on:
  push:
    paths:
      - 'OrderPipelineLayered/**'
      - 'OrderPipelineDemo/**'
      - 'Directory.Build.props'
      - 'Directory.Packages.props'
      - 'global.json'
      - '.github/workflows/orderpipeline-architecture.yml'
  pull_request:
    paths:
      - 'OrderPipelineLayered/**'
      - 'OrderPipelineDemo/**'
      - 'Directory.Build.props'
      - 'Directory.Packages.props'
      - 'global.json'
      - '.github/workflows/orderpipeline-architecture.yml'
  workflow_dispatch:

permissions:
  contents: read

jobs:
  architecture:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-dotnet@v6
        with:
          global-json-file: global.json

      # Debug on purpose: ArchUnitNET reads the compiled IL, and Release builds can drop dependencies.
      - run: dotnet test --project OrderPipelineLayered/OrderPipeline.ArchitectureTests --configuration Debug
Enter fullscreen mode Exit fullscreen mode

There is no container, no Azure Functions Core Tools install and no emulator to wait for, so the job is checkout, SDK, restore, build and about a second of tests. On ubuntu-latest, the run for the commit that added the workflow took 49 seconds: 42 for the test step, of which the seven tests took 1.2 seconds and restore and build the rest. Running separately, it reports a layer violation without waiting for the Testcontainers job. OrderPipelineDemo/** is in the path filter because FirstAttemptTests loads that assembly. With test.runner set to Microsoft.Testing.Platform in global.json, the .NET 10 SDK runs dotnet test in MTP mode, which takes the project through --project.

--configuration Debug is already the default for dotnet test. It is spelled out because the first person who adds -c Release to every test step "to match production" switches off part of what ArchUnitNET can see; the next section shows how much.

A red test only blocks a merge if the check is required. Add the architecture job as a required status check in the branch protection rule or ruleset for main. Before you do, drop the paths: filter in your own repo. GitHub's workflow syntax docs are explicit: a workflow skipped by a path filter leaves its checks "Pending", and a pull request that requires them is blocked from merging. The samples repo keeps the filter because it holds dozens of unrelated samples and none of its checks is required. In an app repo, a check this cheap can run on every pull request.

Gotchas

Program.cs is invisible

The obvious selection for the Functions layer is the whole host assembly, Types().That().ResideInAssembly(typeof(OrderProcessor).Assembly). Rule 3 written that way should fail on day one: Program.cs calls AddInfrastructure, a legitimate dependency on Infrastructure from the composition root. It passes.

Top-level statements compile into a Program class with a compiler-generated <Main>$ method, and ArchUnitNET 0.13.5 leaves that method out of the model. Program shows up with a constructor and two dependencies: object and [CompilerGenerated]. Everything Program.cs registers is invisible.

So the by-assembly rule is green for the wrong reason. Move the registrations into a regular method, an AddOrderPipeline extension in the host project for example, and the same rule fails on code that is allowed to reference Infrastructure. The opposite rule doesn't work either: "only Program may depend on Infrastructure" has nothing to check, because ArchUnitNET never sees Program depend on anything. That is one more reason the sample defines the Functions layer by its [Function] methods instead of by assembly.

Release builds hid every async method body before 0.13.5

This one is fixed, but it still bites if your suite runs an older version or in -c Release. Take a Function that calls new BlobContainerClient(...) inside its async trigger method instead of taking the client through its constructor. With ArchUnitNET 0.13.4, a NotDependOnAny rule against Azure.Storage fails on that class in Debug and passes in Release. In optimized builds the compiler emits the async state machine as a struct, which the loader didn't recognize, so it analyzed only the stub that starts the state machine and lost every call and new in the method body. Most Function trigger methods are async. Constructor dependencies were always found, which is why a suite can look healthy in Release while missing exactly the shortcuts taken inside Run.

The 0.13.5 release notes fix this and warn that upgrading can turn green rules red. Treat that red as a violation that was always there, not as an upgrade regression. The same release makes an And/Or rule fail when either side matches nothing, where before the result depended on the order of the two sides. The project still recommends Debug, because optimized IL drops other dependencies too; the debug artifacts page lists them.

Conclusion

The compiler enforces project references, and code review enforces what fits in a diff. Neither can express the one rule a Function app needs most: the host project may reference Infrastructure, but only its composition root may use it. Five tests in one test class turn it into a failing build on the commit that breaks it, and the CI job needs no containers and finishes in under a minute. Two of them keep the other three honest: one checks that the forbidden sets aren't empty, so a typo can't turn a rule quietly green, and the other keeps the code the Functions SDK generates from tripping the rule about callers.

Architecture tests check how the code is put together. They say nothing about the contract the order pipeline offers its callers: rename a JSON property on Order and every rule here stays green while a consumer breaks. Part 4 tests that contract.

When you write the Functions rule, do you select the Functions layer by assembly or by the [Function] attribute?

Top comments (0)