What are architecture tests and why do they belong in your test suite?

An architecture test is an executable rule about dependency direction: which packages, layers, or modules may depend on which others. It runs with your unit tests and fails the build when the rule is broken. "Controllers may call services but never repositories directly" stops being a line on a wiki page and becomes an assertion against the actual import graph.

Diagrams and code review are weak against this kind of drift. Erosion rarely arrives as one large, obviously wrong change. It arrives as a single convenient import, such as a controller reaching into a repository to skip a service method or a billing module reading an internal class from accounts. Each change is small and has a plausible reason, and the reviewer is focused on the behavior being added, not the dependency it introduces. Months later the diagram still shows clean layers while the code has a dozen exceptions. A test does not get tired or distracted. It checks every import on every build.

The payoff is largest for backend and platform engineers who maintain a growing monolith that several teams change at once. In that setting, nobody holds the whole dependency graph in their head.

Introduce these tests as soon as layers or modules exist on paper, ideally before violations accumulate. They also work on legacy code: record the current violations as a baseline and fail only on new ones. Either way, a boundary argument that used to repeat in review threads becomes a cheap automated check that gives the same answer every time.

How does ArchUnit enforce layered architecture in JVM code?

ArchUnit analyzes bytecode, not source, so the first step is importing compiled classes. Scope the import to your root package (for example com.example.shop) and exclude test classes with ImportOption.DoNotIncludeTests. Test code legitimately reaches across layers to build fixtures, and including it produces violations nobody intends to fix. With JUnit 5, @AnalyzeClasses caches the imported classes and shares them across every @ArchTest rule in the class, so the import cost is paid once. Scope is a trade-off. Importing the whole classpath, including libraries, slows every run and floods results with irrelevant classes. Importing only your own packages is fast, but rules can only reason about classes inside that scope. That limit matters for rules such as "no class may use the JDBC API directly," which have to see the third-party package as a dependency target.

A single rule reads close to English: no classes that reside in ..domain.. should depend on classes that reside in ..web.. or ..persistence.., followed by a because("the domain model must stay framework-independent"). The because clause appears in the failure output, so whoever breaks the rule learns the reasoning without searching for an architecture document.

Once you have more than a few of these rules, switch to layeredArchitecture(). You declare each layer by a package pattern and then state which layers may access it, for example "Persistence may only be accessed by Service." This states the whole policy in one place and closes gaps that a growing list of noClasses() rules tends to leave open.

A violation message names the rule that was broken, followed by one line per offending dependency. Each line gives the source class and member, the target class, and the file and line number. Fix the dependency itself, or change the rule deliberately.

package com.example.shop;

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;

// Import production bytecode under the root package once; the result is cached
// and shared by every @ArchTest field in this class.
@AnalyzeClasses(packages = "com.example.shop",
                importOptions = ImportOption.DoNotIncludeTests.class)
class ArchitectureTest {

    // A single fluent rule. The because() text is printed when the rule fails.
    @ArchTest
    static final ArchRule domainIsFrameworkFree = noClasses()
            .that().resideInAPackage("..domain..")
            .should().dependOnClassesThat().resideInAnyPackage("..web..", "..persistence..")
            .because("the domain model must stay framework-independent");

    // The whole layering policy in one place, in place of many noClasses() rules.
    @ArchTest
    static final ArchRule layers = layeredArchitecture()
            .consideringOnlyDependenciesInLayers() // ignore JDK and library targets
            .layer("Web").definedBy("..web..")
            .layer("Service").definedBy("..service..")
            .layer("Persistence").definedBy("..persistence..")
            .layer("Domain").definedBy("..domain..")
            .whereLayer("Web").mayNotBeAccessedByAnyLayer()
            .whereLayer("Service").mayOnlyBeAccessedByLayers("Web")
            .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service")
            .because("requests flow web -> service -> persistence, never backwards");
}

A JUnit 5 ArchUnit test that imports production classes once, scoped to the root package. It checks a single domain-isolation rule with a because clause, then states the full layering policy with layeredArchitecture().

How do you enforce module boundaries and ban cycles inside a monolith?

Layer rules alone allow a different kind of coupling. Every class in orders can respect web → application → domain and still call deep into billing's internals. A monolith stays maintainable when its features are vertical modules with narrow entry points. The sample application has three top-level packages:

 com.example.orders               com.example.billing
 +------------------------+       +------------------------+
 | web                    |       | web                    |
 |  -> application        |       |  -> application        |
 |      -> domain         |       |      -> domain         |
 | api  <-----------------+-------+  (billing calls orders |
 |  (only entry point)    |       |   only through api)    |
 +-----------+------------+       +-----------+------------+
             |                                |
             v                                v
          +---------------------------------------+
          | com.example.shared                    |
          | (depends on no module)                |
          +---------------------------------------+

The first rule bans cycles between modules. ArchUnit's slice API groups classes by a package pattern, so slices().matching("com.example.(*)..") treats each captured name (orders, billing, shared) as one slice. Adding beFreeOfCycles() fails the build if orders depends on billing while billing also depends on orders, at any distance. Cycles matter more than individual edges because two modules in a cycle can no longer be built, tested or extracted separately.

The second rule protects encapsulation. For each module, classes outside ..billing.. may depend only on classes in ..billing.api... With this rule, billing.domain becomes private by convention backed by a test, and Java's access modifiers are not needed for that. A third rule says that nothing in shared may depend on a module. Without it, shared tends to become the route that cycles take around the slice check.

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

// Production classes only, so test fixtures cannot hide or create violations.
@AnalyzeClasses(packages = "com.example", importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleBoundaryTest {

    // Each first-level package (orders, billing, shared) is one slice.
    // Fails on any cycle between slices, direct or transitive.
    @ArchTest
    static final ArchRule modules_are_free_of_cycles =
            slices().matching("com.example.(*)..").should().beFreeOfCycles();

    // billing internals may only be used from inside billing.
    // Other modules have to go through com.example.billing.api.
    @ArchTest
    static final ArchRule billing_internals_are_private =
            classes().that().resideInAPackage("com.example.billing..")
                    .and().resideOutsideOfPackage("com.example.billing.api..")
                    .should().onlyHaveDependentClassesThat()
                    .resideInAPackage("com.example.billing..");

    // The same rule for orders. Copy it for every module you add.
    @ArchTest
    static final ArchRule orders_internals_are_private =
            classes().that().resideInAPackage("com.example.orders..")
                    .and().resideOutsideOfPackage("com.example.orders.api..")
                    .should().onlyHaveDependentClassesThat()
                    .resideInAPackage("com.example.orders..");

    // shared sits at the bottom of the diagram and must not depend on any module.
    @ArchTest
    static final ArchRule shared_depends_on_no_module =
            noClasses().that().resideInAPackage("com.example.shared..")
                    .should().dependOnClassesThat()
                    .resideInAnyPackage("com.example.orders..", "com.example.billing..");
}

An ArchUnit JUnit 5 test for the sample monolith that bans cycles between the orders, billing and shared slices, allows other modules to reach a module only through its api package, and stops shared from depending on any module.

How do you write dependency-cruiser rules for a TypeScript monolith?

Run npx depcruise --init in the repository root. It asks a few questions about your setup, including whether to use your tsconfig.json, and writes a .dependency-cruiser.js file containing a set of forbidden rules. Keep the starter rules that catch orphans and unresolvable imports, because they guard the tool itself. Then add your own rules. Each rule has a name, a severity (error, warn or info), a comment that explains the intent to whoever breaks it, and from/to objects that match file paths with regular expressions.

The three rules mirror the ArchUnit set:

  • Layer direction. from.path matches ^src/modules/[^/]+/domain/ and to.path matches ^src/modules/[^/]+/http/.
  • Cycles. to: { circular: true } with an empty from applies the ban to every file.
  • Module internals. from.path captures the module name with ^src/modules/([^/]+)/. to.path targets ^src/modules/[^/]+/internal/, and to.pathNot uses $1 to exempt the module's own internal folder.

If you add an import from a domain service into a controller, the run reports the rule name, the importing file, the imported file and the severity, followed by a summary count. In CI, run depcruise src --config .dependency-cruiser.js. Any error-severity violation makes it exit non-zero and fails the job. warn violations are reported but do not fail it.

Path rules match resolved file paths, not the specifiers written in your imports. If options.tsConfig does not point at the tsconfig.json that defines your aliases, an import such as @billing/internal/x does not resolve to a file. No path rule can match it, so the violation passes without any error. To check this, keep the not-to-unresolvable rule at error and confirm that an aliased import shows up in the output.

// .dependency-cruiser.js (trimmed; keep the other starter rules from --init)
module.exports = {
  forbidden: [
    {
      name: 'domain-not-to-http',
      severity: 'error',
      comment: 'Domain code must not depend on controllers; move shared types into domain.',
      from: { path: '^src/modules/[^/]+/domain/' },
      to: { path: '^src/modules/[^/]+/http/' },
    },
    {
      name: 'no-circular',
      severity: 'error',
      comment: 'Cycles make modules impossible to extract or test in isolation.',
      from: {},
      to: { circular: true },
    },
    {
      name: 'no-foreign-internals',
      severity: 'error',
      comment: 'Import another module through its public entry point, not its internal folder.',
      from: { path: '^src/modules/([^/]+)/' },
      to: {
        path: '^src/modules/[^/]+/internal/',
        pathNot: '^src/modules/$1/internal/', // $1 = the importing module's name
      },
    },
    {
      // Starter rule: an unresolved alias would otherwise slip past every path rule
      name: 'not-to-unresolvable',
      severity: 'error',
      from: {},
      to: { couldNotResolve: true },
    },
  ],
  options: {
    doNotFollow: { path: 'node_modules' },
    tsPreCompilationDeps: true,
    // Must point at the tsconfig that defines "paths" (e.g. @billing/*)
    tsConfig: { fileName: 'tsconfig.json' },
  },
};

// CI: exits non-zero on any error-severity violation
// npx depcruise src --config .dependency-cruiser.js

A dependency-cruiser config with the layer, cycle and module-internals rules, plus the not-to-unresolvable guard and the tsConfig reference that lets aliased imports resolve to real paths.

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

Most codebases fail a new layering rule on the first run, often with hundreds of violations. Fixing them all before merging the rule is rarely realistic, so the usual approach is to accept today's violations as a recorded baseline and fail the build only on new ones.

In ArchUnit, you wrap a rule with FreezingArchRule.freeze(...). On the first run, it writes current violations to a violation store, which by default is a set of plain-text files. Later runs compare against that store. A new violation fails the test, and a violation you fix is removed from the store. Commit the store so reviewers see it change. dependency-cruiser uses the same pattern. depcruise-baseline writes a known-violations file, and running with --ignore-known reports only violations missing from that file.

A baseline is useful only if it shrinks. Use these practices:

  • Assign an owner for each frozen rule, usually the team that owns the target layer.
  • Track the count as a trend in CI output or a dashboard. A flat line means nobody is paying it down.
  • Forbid regenerating the baseline without review. Use CODEOWNERS on the store files. Regenerating silently accepts every new violation at once.
  • Tighten once a module is clean. Remove the freeze for that package so the rule applies strictly from then on.

Without these practices, the baseline becomes permanent amnesty that nobody revisits.

The initial setup takes an hour or two. Most of the cost is the ongoing paydown. Illustrative estimate: assume 120 frozen violations, 30 minutes per fix, and 2 hours per week of team time. That is 60 hours, or about 30 weeks, to reach zero.

// Store config lives in src/test/resources/archunit.properties:
//   freeze.store.default.path=src/test/resources/archunit_store
//   freeze.store.default.allowStoreCreation=false  # set true once, locally, to record the baseline
// Commit archunit_store/ and put it under CODEOWNERS so baseline changes get reviewed.
package com.example.arch;

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

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

    // Frozen rule. Existing violations are recorded in the store and tolerated.
    // New violations fail the build. Fixed ones are removed from the store.
    // Owner: platform team.
    @ArchTest
    static final ArchRule layers = freeze(
        layeredArchitecture().consideringAllDependencies()
            .layer("Web").definedBy("..web..")
            .layer("Service").definedBy("..service..")
            .layer("Persistence").definedBy("..persistence..")
            .whereLayer("Web").mayNotBeAccessedByAnyLayer()
            .whereLayer("Service").mayOnlyBeAccessedByLayers("Web")
            .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service"));

    // Billing reached zero violations, so this rule is strict (not frozen).
    // Any regression fails the build immediately.
    @ArchTest
    static final ArchRule billingServiceIgnoresWeb =
        noClasses().that().resideInAPackage("..billing.service..")
            .should().dependOnClassesThat().resideInAPackage("..billing.web..");
}

A JUnit 5 ArchUnit test that freezes a layering rule against a committed violation store while enforcing a strict rule for a module that has already been cleaned up.

When should you avoid relying on architecture tests, and what are their limits?

Architecture tests read the dependency graph that the compiler or bundler can see. Anything resolved at runtime is invisible to them. That includes reflection, DI containers that wire beans by name or classpath scan, dynamic import() with computed paths, service-locator lookups, two modules sharing database tables, and events whose publisher and subscriber never reference each other. A module can be fully decoupled in the import graph and still be tightly coupled in production.

Rules also depend on naming. A layer defined as "packages ending in .service" or "files under src/domain" stops matching after a rename, and an empty match fails nothing. Add a guard test that asserts each layer pattern matches at least one class or file. ArchUnit can also be configured to fail rules whose selection is empty.

Over-specified rules backfire. If every helper needs an exemption, engineers add broad ignore patterns, and enforcement erodes quietly.

Limitation Symptom Mitigation
Static analysis only Coupling through DI, events, or shared tables Make each table owned by one module, review runtime wiring separately
Load-bearing names Rule passes after a refactor because nothing matches Assert every layer pattern is non-empty
Over-specification Growing exemption lists Keep rules few and coarse, require a reason for each exemption
Polyglot monolith JVM and TypeScript rule sets drift apart Define boundaries once in a shared doc, review both rule sets together
Green build ≠ good design Poor module splits frozen in place Revisit rules when module boundaries change

A passing suite shows that the code matches the rules. It does not show that the rules describe a good design.

What are the alternatives to ArchUnit and dependency-cruiser, and how do you keep rules maintainable?

Architecture tests are one option among several, and they combine well with the others.

Approach What it catches Setup cost Refactoring friction
Code review and diagrams Whatever reviewers notice Low Low, but drift goes unnoticed
Separate Gradle/Maven modules or workspace packages Undeclared dependencies, at compile or install time Medium to high High: moving code means changing build files
Java modules or package-private classes Access to non-exported or non-public types Medium Medium: visibility changes ripple through callers
Import lint rules Forbidden import paths in the editor and CI Low Low
Splitting into services Direct calls across a network boundary Very high Very high: contracts, deployment, data ownership

Build-level separation and language visibility give the strongest guarantees because the compiler enforces them. They are also the hardest to change if you draw a boundary in the wrong place. Architecture tests and lint rules cost less to adjust, so they suit boundaries you are still settling. Once a boundary has proven stable, you can promote it to a module.

Keeping rules maintainable

  • Name each rule after the decision it protects. "Billing does not read Orders persistence" is clearer than "rule 14".
  • Record the rationale in the because clause or a comment. Without it, a later reader can't tell a rule that still matters from one nobody needs.
  • Keep all rules in one place owned by a team, so no one adds or removes them silently.
  • Review rule changes like production code. Loosening a rule is an architectural decision.
  • Write failure messages for newcomers. State the intended dependency direction and what to do instead, such as moving the class or calling the module's public API.

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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.