What are ArchUnit architecture tests and how do they work?

ArchUnit is a Java library that tests the structure of your code instead of its behavior. It reads compiled bytecode, not source files. You can load classes yourself with ClassFileImporter, or let the JUnit integration do it by annotating a test class with @AnalyzeClasses and marking rule fields or methods with @ArchTest. ArchUnit builds an in-memory model of classes, methods, fields, and their relationships, and checks your rules against that model.

Working from bytecode matters because it shows the real dependencies. A source-level check that scans import statements misses fully qualified references, same-package access, and types used only through inheritance or method signatures. ArchUnit sees field types, method calls, constructor calls, superclasses, implemented interfaces, annotations, and thrown exceptions. There is one known blind spot. The Java compiler inlines compile-time constants such as static final strings and primitives, so a dependency that exists only through such a constant leaves no trace in the bytecode.

Each rule works as an architecture fitness function: an automated check that the system still has a property you care about. These rules run in your ordinary unit test suite with the same runner and the same CI step, and a violation fails the build like any other test.

This is why boundaries in a modular monolith hold only when they are executable. Diagrams and wiki pages don't fail pull requests. When several teams commit to one codebase under deadline pressure, a shortcut across a layer compiles and passes review, and then it stays. Backend and platform engineers who own a shared codebase get the most from ArchUnit, because the build enforces the rules for them.

How do you write your first ArchUnit rule?

Start with a single rule that states one design decision. With static imports from ArchRuleDefinition, the chain reads almost as prose: noClasses().that().resideInAPackage("..domain..").should().dependOnClassesThat().resideInAPackage("..web.."). The that() clause selects the classes under test, and the should() clause states what they must not do. Because the rule starts with noClasses(), every matching dependency counts as a violation.

The strings are package identifiers, not regular expressions. .. matches any number of package segments, including none, and * matches characters within a single segment. So ..domain.. matches com.acme.domain and com.acme.billing.domain.invoice, but not com.acme.domainevents, because domain must be a whole segment. That is usually what you want in a monolith where every module has its own domain package.

Put rules in a dedicated test class annotated with @AnalyzeClasses, and declare each rule as a static final ArchRule field marked @ArchTest. Set packages to your root package and pass ImportOption.DoNotIncludeTests.class in importOptions. Test fixtures often reach across layers on purpose, and you don't want them reported as violations. For generated code, write a small ImportOption that rejects any location whose path contains your generated-sources directory. You don't own that code, so a rule failing on it only produces noise.

Finally, append .because(...) with the decision and the fix, for example: "domain must stay independent of HTTP; move request mapping into a web adapter." The failure message then explains the decision and tells the developer what to change.

package com.acme.architecture;

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.core.importer.Location;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

// Import production classes under com.acme only: skip test classes
// (fixtures may cross layers on purpose) and generated code we don't own.
@AnalyzeClasses(
        packages = "com.acme",
        importOptions = {
                ImportOption.DoNotIncludeTests.class,
                LayerRulesTest.ExcludeGeneratedSources.class
        })
class LayerRulesTest {

    // '..domain..' matches com.acme.domain and com.acme.billing.domain.invoice,
    // but not com.acme.domainevents: 'domain' must be a whole package segment.
    @ArchTest
    static final ArchRule domain_must_not_depend_on_web =
            noClasses().that().resideInAPackage("..domain..")
                    .should().dependOnClassesThat().resideInAPackage("..web..")
                    // Name the design decision and the fix in the failure message.
                    .because("domain must stay independent of HTTP; "
                            + "move request mapping into a web adapter");

    // Rejects classes compiled from the build's generated-sources directory.
    // ArchUnit instantiates import options reflectively, so the class needs
    // to be public with a no-arg constructor.
    public static class ExcludeGeneratedSources implements ImportOption {
        @Override
        public boolean includes(Location location) {
            return !location.contains("/generated-sources/");
        }
    }
}

A dedicated JUnit 5 ArchUnit test class imports only production classes from com.acme, excluding tests and generated sources. It declares one rule: domain packages must not depend on web packages, with a because() clause that names the design decision and the fix.

How do you enforce layer dependency rules with layeredArchitecture()?

Declare each layer as a set of packages, then state who may call into it. A package belongs to a layer through layer("Domain").definedBy("..domain.."), and the access rules go in whereLayer("Domain").mayOnlyBeAccessedByLayers("Application", "Infrastructure"). ArchUnit fails any dependency that the rules do not allow.

  web ─────────► application ─────────► domain
                      ▲                    ▲
                      │                    │
  infrastructure ─────┴────────────────────┘

The matching rule:

  • Web mayNotBeAccessedByAnyLayer().
  • Application mayOnlyBeAccessedByLayers("Web", "Infrastructure").
  • Domain mayOnlyBeAccessedByLayers("Application", "Infrastructure").
  • Infrastructure mayNotBeAccessedByAnyLayer(). The DI container wires its adapters to the ports they implement, so no application code needs to reference them.

List the allowed edges rather than every forbidden one. Four layers allow twelve possible directed edges. A deny-list has to name each bad edge, and when you add a fifth layer it permits every edge into and out of that layer until someone remembers to forbid them. An allow-list fails closed: a new package that nobody assigned to a layer cannot reach the domain by accident. The rule also reads like the diagram, so reviewers can check one against the other.

Some exceptions are deliberate. Suppose AdminController uses ReportQueryDao directly for a read-only export, and the team has agreed to keep it. Write ignoreDependency(AdminController.class, ReportQueryDao.class) for it. Do not widen Web's access to all of Infrastructure. The exemption covers one class pair, so a second controller that tries the same shortcut still fails the build. The exemption also stays visible in the test, where it shows up in code review and can be deleted once the export is moved behind an application service.

package com.example.shop.architecture;

import com.example.shop.infrastructure.reporting.ReportQueryDao;
import com.example.shop.web.AdminController;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.library.Architectures.layeredArchitecture;

@AnalyzeClasses(packages = "com.example.shop")
class LayerDependencyTest {

    @ArchTest
    static final ArchRule layers_follow_the_diagram = layeredArchitecture()
            .consideringAllDependencies()
            // Each layer is a set of packages.
            .layer("Web").definedBy("..web..")
            .layer("Application").definedBy("..application..")
            .layer("Domain").definedBy("..domain..")
            .layer("Infrastructure").definedBy("..infrastructure..")

            // Allowed edges only. Anything not listed here fails the build.
            .whereLayer("Web").mayNotBeAccessedByAnyLayer()
            .whereLayer("Application").mayOnlyBeAccessedByLayers("Web", "Infrastructure")
            .whereLayer("Domain").mayOnlyBeAccessedByLayers("Application", "Infrastructure")
            // Adapters are wired by the DI container, so no layer references them.
            .whereLayer("Infrastructure").mayNotBeAccessedByAnyLayer()

            // Deliberate exception: read-only admin export, agreed by the team.
            // Scoped to one class pair; other controllers using
            // ReportQueryDao still fail.
            .ignoreDependency(AdminController.class, ReportQueryDao.class);
}

A JUnit 5 ArchUnit test that declares four package-based layers, lists only the permitted access edges from the diagram, and exempts the single AdminController-to-ReportQueryDao dependency with ignoreDependency.

How can ArchUnit enforce Java module boundaries inside a monolith?

Layer rules describe how code is stacked inside a feature. They say nothing about how features depend on each other, and in a monolith that is usually where coupling grows fastest. If your packages follow a feature-first layout such as com.example.orders, com.example.billing and com.example.inventory, ArchUnit can treat each top-level package as a module.

Detecting cycles between modules

slices().matching("com.example.(*)..") groups every class into a slice named after the package segment captured by (*). Adding .should().beFreeOfCycles() fails the test whenever slices depend on each other in a loop, for example orders → billing → inventory → orders. Cycles matter because they prevent you from building, testing, or extracting any module on its own. Once two modules form a cycle, they behave as a single module that happens to live in two packages.

Restricting access to a designated api package

Avoiding cycles does not stop billing from reaching into orders.internal.persistence. To prevent that, give each module an api subpackage and write a rule that applies to all code outside the module. The rule says that classes residing outside com.example.orders.. must not depend on classes in com.example.orders.. unless those classes are in com.example.orders.api... Write one such rule per module, or generate them in a loop. The effect is similar to Java's module-level encapsulation, without splitting the build into separate artifacts.

Expect a noisy first report

On an existing codebase, the first cycle report can run to hundreds of lines. ArchUnit lists the class-level dependencies behind every edge in a cycle, and overlapping cycles repeat the same edges. Before the output is actionable, someone has to work out which dependencies are deliberate and which modules are really one module, then rank the fixes by how much they cost. Plan for that analysis to take real time, and don't expect the first run to give you a clean backlog.

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;

@AnalyzeClasses(packages = "com.example", importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleBoundaryTest {

    // Each top-level package (orders, billing, inventory, ...) becomes one slice.
    // Fails if any slices depend on each other in a loop.
    @ArchTest
    static final ArchRule modules_are_free_of_cycles =
            slices().matching("com.example.(*)..").should().beFreeOfCycles();

    // One rule per module: outside code may only use that module's api package.
    @ArchTest static final ArchRule orders_api_only = onlyApiAccessible("orders");
    @ArchTest static final ArchRule billing_api_only = onlyApiAccessible("billing");
    @ArchTest static final ArchRule inventory_api_only = onlyApiAccessible("inventory");

    private static ArchRule onlyApiAccessible(String module) {
        String root = "com.example." + module + "..";
        String api = "com.example." + module + ".api..";
        return noClasses()
                .that().resideOutsideOfPackage(root)
                .should().dependOnClassesThat(
                        resideInAPackage(root).and(not(resideInAPackage(api))))
                .because(module + " internals are private; depend on " + api + " instead");
    }
}

A JUnit 5 ArchUnit test that fails on cycles between feature-module slices and restricts cross-module dependencies to each module's api package.

How do you adopt ArchUnit on a legacy codebase without breaking the build?

A ruleset that fails on day one gets disabled by the end of the week. The workable approach is to make today's state the baseline and fail only on regressions.

Freeze what exists, block what's new

Wrap each rule in FreezingArchRule. On the first run, it records current violations in a violation store, a set of plain-text files configured through archunit.properties. Later runs fail only on violations that are not in the store, and they remove entries once the underlying code is fixed. Commit the store so that CI and every developer check against the same baseline, and treat each shrinking diff as visible progress.

The store has costs. Without an owner, it becomes a permanent amnesty that nobody reviews. Assign each store file to a team and review its size on a regular schedule. When many teams touch one store, expect merge conflicts and noisy diffs. Splitting stores per rule or per module reduces both.

Share rules, keep imports cheap

In a multi-module build, put rule definitions in a shared test library. Each module can then pull them in with ArchTests.in(...) instead of copying them. Scope @AnalyzeClasses to your own root packages and exclude test classes with ImportOption, so the import skips the JDK and third-party jars. The JUnit integration caches the import, so put rules as @ArchTest fields on one class rather than re-importing in every method.

The payoff is timing. A failing test catches a new cross-layer call in seconds, at the moment the author still has context. Without the test, that call only gets caught if a reviewer happens to notice it, or it gets untangled months later during a refactoring.

// shared-arch-rules module (test library): com/example/arch/LayerRules.java
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.library.freeze.FreezingArchRule;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;

public final class LayerRules {
    // freeze(): existing violations go to the store, only new ones fail the build.
    // A stable description (.as) keeps this rule's entries in its own store file.
    @ArchTest
    public static final ArchRule layers = FreezingArchRule.freeze(
        layeredArchitecture().consideringAllDependencies()
            .layer("Web").definedBy("com.example..web..")
            .layer("Service").definedBy("com.example..service..")
            .layer("Persistence").definedBy("com.example..persistence..")
            .whereLayer("Web").mayNotBeAccessedByAnyLayer()
            .whereLayer("Service").mayOnlyBeAccessedByLayers("Web")
            .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service")
            .as("Layer dependencies follow web -> service -> persistence"));
}

// billing module: src/test/java/com/example/billing/BillingArchitectureTest.java
import com.example.arch.LayerRules;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.junit.ArchTests;

// Import only our own production classes; JDK, third-party jars and tests are skipped.
// The import runs once for this class and is reused by every @ArchTest field.
@AnalyzeClasses(packages = "com.example.billing",
                importOptions = ImportOption.DoNotIncludeTests.class)
class BillingArchitectureTest {
    @ArchTest
    static final ArchTests layerRules = ArchTests.in(LayerRules.class);
}

// billing module: src/test/resources/archunit.properties
//   freeze.store.default.path=src/test/resources/archunit_store
//   freeze.store.default.allowStoreCreation=true
// Commit archunit_store/ so CI and developers check against the same baseline.

A frozen layer rule defined once in a shared test library, pulled into a module with ArchTests.in and a narrowly scoped @AnalyzeClasses import, with the violation store location set in that module's archunit.properties.

Which rule categories beyond layers pay off in a monolith?

Layer rules catch the structural mistakes. The next most useful rules target the small habits that quietly erode a design. Each rule below works best when it encodes one decision the team has already made and can explain.

Rule category Example rule Decision it protects
Naming tied to packages Classes ending in Repository reside only in ..infrastructure.. Readers can infer a class's role and dependencies from its name
Framework annotations confined to adapters Classes annotated with @Entity stay in ..infrastructure.persistence.. and are not referenced from ..domain.. or ..api.. Persistence entities never leave the infrastructure layer, so schema changes don't ripple into business logic or API contracts
Banned APIs in domain code No domain class calls System.currentTimeMillis() or LocalDateTime.now() Time is injected (for example via java.time.Clock), so domain logic stays deterministic under test
Banned APIs in domain code Domain code depends only on a logging facade, never on a concrete logging implementation The logging backend can change without touching business code

The naming rule matters more than it looks. When OrderRepository can show up in any package, the name stops telling you where the class lives or what it depends on. The clock ban pays off the first time someone debugs a test that fails only around midnight.

Review rule changes like production code. A pull request that loosens a rule should say which design decision changed and why. A pull request that adds a rule should name the decision it encodes. Rules also go stale. If the team has abandoned a design, for example by merging two modules that used to be separate, delete the rules that enforced it. A stale rule that everyone works around teaches people to ignore the whole suite.

When should you avoid ArchUnit, and what are the alternatives?

ArchUnit only sees what the compiler leaves in bytecode. It cannot detect a dependency created through reflection, a bean wired by the dependency injection container from configuration, or a class loaded by name from a string. If your layers talk to each other mainly through those mechanisms, a passing ArchUnit suite gives you false confidence.

Rules are also only as good as the package layout. When one package mixes controllers, entities and helpers, no rule can tell them apart. In that case, restructure the packages first and write rules after. Rules that are too strict cause a different problem. Developers under deadline pressure move code into a package no rule covers, such as util or common. The build stays green while the architecture gets worse.

The main alternative is to make the illegal dependency impossible rather than detectable. With separate build modules, a module can only import code from modules it declares as dependencies. The Java module system goes further: a module can use only the packages another module explicitly exports.

Approach When violations surface Cost of moving a boundary Best fit
ArchUnit rules Test run Edit a rule Boundaries still being discovered
Separate build modules Compile time Restructure build files and move code Stable, well-understood components
Java module system Compile time and run time Edit module descriptors and exports Stable boundaries needing strong encapsulation

Use ArchUnit while the boundaries are still changing, because adjusting a rule costs little. Once a boundary has held for a while, promote it to a build module so the compiler enforces it.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to archunit architecture tests, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.