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. You describe a constraint, such as "classes in ..domain.. must not depend on classes in ..web..", and ArchUnit fails the build when any class breaks it.

It works on compiled bytecode, not source files. A ClassFileImporter reads .class files from the classpath or from given locations and builds an in-memory graph of JavaClasses. Each class records its fields, methods, annotations, superclasses, and every class it references. With the JUnit integration, you annotate a test class with @AnalyzeClasses and declare rules as @ArchTest fields or methods. The integration imports the classes and caches the result, so many rules can share one import.

A rule is a fluent expression built from ArchRuleDefinition. You select a set of classes, then state what they should or should not do. Evaluating the rule walks the graph and collects every violating dependency. The failure message names the source class, the target class, and the line where the reference appears.

Because rules are ordinary unit tests, they run in the normal test phase of Maven or Gradle. You need no separate tool, server, or CI step.

The main limit comes from that same mechanism: ArchUnit sees only dependencies that exist in bytecode. It cannot see reflection, classes loaded by name at runtime, wiring defined in configuration files, or which bean a framework injects at runtime. The compiler also inlines constant static final values, so a reference to such a constant leaves no trace in the class file.

Why do package boundaries erode in a monolith, and who should enforce them?

Boundaries in a monolith rarely break through a deliberate design decision. They break one import at a time. A developer in billing needs a customer's display name, the IDE suggests com.example.crm.internal.CustomerEntity, and accepting the autocomplete takes one keystroke. The code compiles, the tests pass, and the feature ships. Nothing in the toolchain treats that line as different from any other import.

Code review rarely catches it. Reviewers read the logic of a diff, and import blocks are often collapsed or skimmed. A reviewer would also need to remember which packages are internal to which module. In a codebase with several feature teams, no single reviewer holds that map. Each violation also looks harmless on its own. The damage only becomes visible when someone tries to extract crm into its own service, or change its persistence model, and finds dozens of callers reaching into its internals.

That is why the audience for these tests is backend and platform teams that own a shared codebase with multiple contributors. The tests write down the boundaries that until now lived in people's heads. Adopt them once those boundaries exist and are worth protecting. If you have no agreed module structure yet, decide on one first.

The cost difference is a matter of timing. As an illustrative estimate, with assumed inputs: removing a forbidden import in the same pull request might take ten minutes. Untangling forty such references six months later, after other code has been built on top of them, could take days of refactoring and coordination between teams.

How do you write your first forbidden-dependency rule?

Start with a single test class annotated @AnalyzeClasses(packages = "com.example.shop", importOptions = ImportOption.DoNotIncludeTests.class), and declare the rule as a static final ArchRule field marked @ArchTest. The rule reads almost like the policy itself: noClasses().that().resideInAPackage("..domain..").should().dependOnClassesThat().resideInAPackage("..web.."). Append .because("domain logic must not know how it is exposed over HTTP"). The reason appears in the failure message, so whoever hits the failure sees why the boundary exists.

Reading the failure

A violation lists each offending dependency with the source member, the target type, and a file and line number. For example, it names a method in an Order class whose return type is OrderDto and gives the location as Order.java:42. Each line points to a specific field, method signature, or call that needs to change, not just to a class.

Import scope

Test classes often wire domain and web code together on purpose, so exclude them. Generated sources, such as mappers or OpenAPI clients, should also be excluded. Write a small custom ImportOption that rejects their output location. Keep the packages value aligned with the real production root package. A typo or a stale package name imports nothing, and a rule checked against nothing will pass.

Empty sets

The same risk applies to a that() clause that matches no classes. Current ArchUnit releases fail such rules by default, controlled by the archRule.failOnEmptyShould property. Do not turn that off globally. If one rule legitimately matches nothing, call .allowEmptyShould(true) on that rule only.

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;

// Must be the real production root package. A typo here imports nothing.
@AnalyzeClasses(
        packages = "com.example.shop",
        importOptions = {
                ImportOption.DoNotIncludeTests.class,       // tests wire layers together on purpose
                DomainBoundaryTest.ExcludeGenerated.class   // skip mapper and OpenAPI output
        })
class DomainBoundaryTest {

    @ArchTest
    static final ArchRule domainDoesNotDependOnWeb =
            noClasses().that().resideInAPackage("..domain..")
                    .should().dependOnClassesThat().resideInAPackage("..web..")
                    // Printed in the failure message next to each violation
                    .because("domain logic must not know how it is exposed over HTTP");
    // No allowEmptyShould(true) here. If '..domain..' matches nothing,
    // the rule fails by default (archRule.failOnEmptyShould) instead of passing vacuously.

    // Rejects classes whose location is the package that generated code is written to.
    // Adjust the path fragment to match your generator's configured output package.
    static final class ExcludeGenerated implements ImportOption {
        @Override
        public boolean includes(Location location) {
            return !location.contains("/com/example/shop/generated/");
        }
    }
}

A minimal JUnit 5 ArchUnit test that forbids domain-to-web dependencies with a stated reason. It excludes test classes and generated code from the import and leaves the default fail-on-empty-should behavior on so the rule cannot pass vacuously.

How do you enforce layer dependency rules and Spring architecture constraints?

Single-class rules catch individual mistakes. The more durable win is declaring the whole layer model once with layeredArchitecture(). You name each layer by package pattern, for example Controller as ..web.., Service as ..service.. and Persistence as ..persistence... Then you state the allowed callers. Mark Controller with mayNotBeAccessedByAnyLayer(), allow Service to be accessed only by Controller, and allow Persistence to be accessed only by Service.

That last constraint encodes the most common Spring shortcut: a controller that injects a repository "just for this one lookup." The shortcut skips the service layer, along with its transaction boundary and any authorization or validation logic. Because the rule is expressed as who may access persistence, it blocks the shortcut without naming individual repositories. Calling consideringAllDependencies() makes the rule check field types, method parameters and return types as well as method calls, so an injected repository field counts as a violation even if it is never invoked.

The domain core needs a separate noClasses() rule. Classes in ..domain.. should not depend on org.springframework.web.., org.springframework.data.. or jakarta.persistence... Add javax.persistence.. if older code still uses that namespace. This keeps @Entity mappings, ResponseEntity and Pageable out of the domain core. As a result, domain logic stays testable without a container, and a change to persistence or HTTP code cannot ripple into business rules.

Prefer package-based rules over annotation-based ones where you can. Annotation rules are fragile because Spring relies heavily on meta-annotations. A rule written as beAnnotatedWith(Controller.class) misses @RestController and your own composed stereotypes. beMetaAnnotatedWith covers those cases. Even so, it still misses behavior applied indirectly, such as through a superclass or through bean registration in Java configuration.

package com.example.shop.architecture;

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.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;

// Analyze production classes only, so test helpers cannot trigger false violations.
@AnalyzeClasses(packages = "com.example.shop", importOptions = ImportOption.DoNotIncludeTests.class)
class ArchitectureTest {

    // Declare the layer model once, by package rather than by annotation.
    @ArchTest
    static final ArchRule layers = layeredArchitecture()
            // Check field types, parameters and return types as well as calls,
            // so an injected repository field fails even if it is never invoked.
            .consideringAllDependencies()
            .layer("Controller").definedBy("..web..")
            .layer("Service").definedBy("..service..")
            .layer("Persistence").definedBy("..persistence..")
            .whereLayer("Controller").mayNotBeAccessedByAnyLayer()
            .whereLayer("Service").mayOnlyBeAccessedByLayers("Controller")
            // Blocks the controller-injects-repository shortcut without naming repositories.
            .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");

    // Keep HTTP, Spring Data and JPA types (ResponseEntity, Pageable, @Entity) out of the domain core.
    @ArchTest
    static final ArchRule domainIsFrameworkFree = noClasses()
            .that().resideInAPackage("..domain..")
            .should().dependOnClassesThat().resideInAnyPackage(
                    "org.springframework.web..",
                    "org.springframework.data..",
                    "jakarta.persistence..",
                    "javax.persistence.."); // legacy namespace, if still present
}

A JUnit 5 ArchUnit test that defines Controller, Service and Persistence layers by package, forbids controllers from accessing persistence directly, and keeps Spring Web, Spring Data and JPA types out of the domain package.

How can you enforce Java module boundaries with package-by-feature slices?

Layers describe the technical shape of a request. Most monoliths also need a second axis: feature modules such as orders, billing and catalog, each grouping its own controllers, services and persistence. ArchUnit models these with slices. slices().matching("..app.(*)..") treats each first-level package under app as one slice, and should().beFreeOfCycles() fails the build when orders depends on billing and billing depends back on orders. Cycles are worth blocking first because they prevent you from extracting or reasoning about any one module on its own. Once two features are cyclic, they are effectively a single module with two names.

Blocking cycles still allows a one-directional dependency on another feature's internals. Give each feature an api package and an internal package, then write a rule per feature, or a generated set of rules, saying that classes outside ..orders.. must not depend on classes in ..orders.internal... Other features then reach orders only through the types it chose to expose. The owning team can then change everything in internal without breaking callers.

The shared-kernel problem

Every slice rule eventually gains an exemption for common, shared or util. These packages become dependency magnets. Anything two features both need ends up there, and because the rules ignore it, it grows without limit. Over time, coupling that the slice rules would have blocked moves into the shared package, where no rule checks it. ArchUnit can freeze the package or limit what it may import. It cannot tell you whether a Money type belongs in the kernel or whether a CustomerLookup helper is a hidden feature dependency. That is a design decision, and it needs an owner who reviews additions to the package.

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.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;

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

    // Each first-level package under app (orders, billing, catalog, common) is one slice.
    // A cycle between any two slices fails the build.
    @ArchTest
    static final ArchRule features_are_free_of_cycles =
            slices().matching("..app.(*)..").should().beFreeOfCycles();

    // Other features may use orders.api, but never orders.internal.
    @ArchTest
    static final ArchRule orders_internals_are_private =
            noClasses().that().resideOutsideOfPackage("..app.orders..")
                    .should().dependOnClassesThat().resideInAPackage("..app.orders.internal..")
                    .because("callers must go through orders.api");

    // Same rule for billing; repeat per feature or generate from a list.
    @ArchTest
    static final ArchRule billing_internals_are_private =
            noClasses().that().resideOutsideOfPackage("..app.billing..")
                    .should().dependOnClassesThat().resideInAPackage("..app.billing.internal..");

    // The shared kernel may depend only on itself and the JDK. This stops it from
    // importing features, but it cannot decide what deserves to live there.
    @ArchTest
    static final ArchRule common_depends_on_nothing_feature_specific =
            classes().that().resideInAPackage("..app.common..")
                    .should().onlyDependOnClassesThat().resideInAnyPackage("..app.common..", "java..");
}

A JUnit 5 ArchUnit test that blocks cycles between feature slices, keeps each feature's internal package private to that feature, and stops the shared common package from depending on any feature.

How do you adopt ArchUnit in a codebase that already has violations?

That owner also decides how to introduce rules into code that already breaks them. Failing the build on day one is rarely an option, so wrap each rule with FreezingArchRule.freeze(...). On the first run, ArchUnit records every existing violation in a violation store, which is plain text files under archunit_store by default. On later runs, only violations missing from the store fail the test. When someone fixes a recorded violation, ArchUnit removes it from the store automatically, so the baseline can shrink but cannot quietly grow.

Commit the store alongside the code. Store creation is off by default (freeze.store.default.allowStoreCreation in archunit.properties), so enable it once to generate the baseline, then turn it off again so CI cannot silently create a fresh one. Put the store directory in your code-ownership file so the architecture owner reviews every change to it. Matching ignores line numbers, which cuts down on churn. When two branches both touch the store, regenerate it instead of hand-merging the conflict. Track the store's size over time. A baseline that never shrinks has stopped being a migration plan and become permanent debt.

Keep rules in a dedicated test package or module as reusable ArchRule fields annotated with @ArchTest, and run them on every change. The setup cost is small. The main recurring cost is CI time spent importing a large classpath. Scope @AnalyzeClasses to your own root packages, exclude tests and JARs with ImportOption, and share one set of locations across test classes so the cached class graph is reused instead of rebuilt.

package com.example.shop.architecture;

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 com.tngtech.archunit.library.freeze.FreezingArchRule;

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

// Scope the import to our own root package and skip test classes and JARs.
// Reuse these exact locations in every architecture test class so ArchUnit
// reuses the cached class graph instead of re-importing the classpath.
@AnalyzeClasses(
        packages = "com.example.shop",
        importOptions = {ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class})
class ModuleBoundaryTest {

    // Plain rule: no existing violations, so it fails on any breach.
    @ArchTest
    static final ArchRule catalog_does_not_use_orders =
            noClasses().that().resideInAPackage("..catalog..")
                    .should().dependOnClassesThat().resideInAPackage("..orders..");

    // Frozen rule: existing violations live in the committed violation store.
    // Only new violations fail. Fixed ones are removed from the store automatically.
    // Generate the baseline once by setting this in src/test/resources/archunit.properties:
    //   freeze.store.default.allowStoreCreation=true
    // then set it back to false so CI cannot create a fresh, empty baseline.
    @ArchTest
    static final ArchRule orders_does_not_reach_into_billing_internals =
            FreezingArchRule.freeze(
                    noClasses().that().resideInAPackage("..orders..")
                            .should().dependOnClassesThat().resideInAPackage("..billing.internal.."));
}

A JUnit 5 ArchUnit test class with a scoped, cache-friendly import, one strict rule, and one rule wrapped in FreezingArchRule so existing violations are baselined while new ones fail the build.

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

ArchUnit reads bytecode, so it only sees dependencies the compiler recorded. It misses calls made through reflection, beans fetched by name from the application context, implementations chosen at runtime by configuration, coupling through events, and two modules reading the same database table. A green build shows the import graph is clean. It does not show the modules are decoupled.

Rules also depend on package names. If someone renames ..billing.. to ..invoicing.., a rule written against the old name can pass because it no longer matches any classes. Make sure rules that match nothing fail the build. Strict rules have a second cost: when every refactor trips one, developers add freeze entries and exclusions until little is actually enforced. Keep only the rules your team would defend in review.

Don't encode a module split you haven't validated yet. Rules make boundaries more expensive to change, and that hurts when the boundaries are in the wrong place.

Approach What it enforces Cost
ArchUnit Static class and package dependencies, checked at test time Blind to runtime coupling; relies on package names
JPMS modules Exported packages, enforced by compiler and runtime Friction with reflection-heavy frameworks; module-info upkeep
Separate build modules Compile-time dependency graph Slower builds; more build configuration
Code review conventions Whatever reviewers notice Inconsistent; doesn't scale
Separate services Hard process and data isolation Network failures, distributed transactions, operational load

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.