On this page
- What an architecture test checks
- Architecture fitness functions
- Architecture rules by tool
- ArchUnit (Java)
- ArchUnitNET (.NET)
- dependency-cruiser (JavaScript and TypeScript)
- Nx module boundaries (TypeScript monorepos)
- import-linter (Python)
- go-arch-lint (Go)
- The tools side by side
- Running architecture tests in CI
- What import rules cannot see
- Cycles that grow slowly
- Decisions the code drifts from
- Changes that deserve a higher bar
- Where repowise fits
- FAQ
Layers erode one import at a time. Nobody decides to collapse the design. A developer needs one helper that lives in the wrong package, the import compiles, the review is about something else, and six months later the "layered" system has edges in every direction. A rule that fails on that first import is far cheaper than the refactor that follows the thousandth.
Architecture testing is the practice of writing automated tests that fail when code breaks a structural rule: the UI layer must not import the database layer, one service must not reach into another's internals, a package must not depend on its own callers. The rules run in CI like any unit test, so the architecture on the whiteboard and the architecture in the repo cannot drift apart without someone seeing a red build. Java teams know the idea as ArchUnit; every other major language has an equivalent.
We build repowise, so weigh our entry accordingly. The measurements we publish about it, with their methods, are on the benchmarks page.
What an architecture test checks
An architecture rule has two parts: a way to pick a set of code (a package, a folder, a tag) and a statement about what that set may depend on. Most rules fall into three families.
- Layer rules. Controllers may call services, services may call repositories, never the reverse.
- Boundary rules. Module A may only use module B through its public entry point.
- Hygiene rules. No import cycles, production code never imports test code, nothing imports from a
deprecatedfolder.
The check is static. The tool reads the compiled classes or the source imports, builds a dependency graph, and compares it with your rules. No code runs, so these tests are fast enough for every commit. For background on the graph itself, see the dependency graph glossary entry.
Architecture fitness functions
An architectural fitness function, a term from Neal Ford, Rebecca Parsons and Patrick Kua's book Building Evolutionary Architectures, is any automated check that measures how well a system meets an architectural goal. A layering rule is a fitness function. So is a test that fails if a service's p99 latency crosses a threshold, or if the build time doubles.
The two phrases overlap heavily in practice. Architecture tests are the structural, cheap-to-run subset of fitness functions, and teams adopt them first because they need no environment, only the code. The rest of this guide stays on the structural kind.
Architecture rules by tool
Every snippet below follows the tool's own documentation as of November 2026. The packages and folders are placeholders.
ArchUnit (Java)
ArchUnit is a Java library that runs as a JUnit test. Its layered architecture API declares layers by package and states who may access them.
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
@AnalyzeClasses(packages = "com.myapp")
public class ArchitectureTest {
@ArchTest
public static final ArchRule layered_architecture_rule = layeredArchitecture()
.consideringAllDependencies()
.layer("Controller").definedBy("..controller..")
.layer("Service").definedBy("..service..")
.layer("Persistence").definedBy("..persistence..")
.whereLayer("Controller").mayNotBeAccessedByAnyLayer()
.whereLayer("Service").mayOnlyBeAccessedByLayers("Controller")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
}
@AnalyzeClasses imports the classes once and each @ArchTest field is one rule, so mvn test or gradle test fails the build on a violation. If you only know the name: that is what an ArchUnit is, a library whose rules are Java code, checked by your existing test runner.
ArchUnitNET (.NET)
ArchUnitNET is the .NET port by the same company. You load assemblies once, then check rules against them from xUnit, NUnit or MSTest.
using ArchUnitNET.Domain;
using ArchUnitNET.Fluent;
using ArchUnitNET.Loader;
using Xunit;
using static ArchUnitNET.Fluent.ArchRuleDefinition;
public class ArchitectureTests
{
// Load once: building the architecture is the slow part.
private static readonly Architecture Architecture = new ArchLoader()
.LoadAssemblies(typeof(OrdersController).Assembly)
.Build();
private readonly IObjectProvider<IType> WebLayer =
Types().That().ResideInNamespace("MyApp.Web").As("Web layer");
private readonly IObjectProvider<IType> DataLayer =
Types().That().ResideInNamespace("MyApp.Data").As("Data layer");
[Fact]
public void Web_should_not_touch_data()
{
Types().That().Are(WebLayer).Should().NotDependOnAny(DataLayer)
.Because("web goes through the service layer")
.Check(Architecture);
}
}
dependency-cruiser (JavaScript and TypeScript)
dependency-cruiser keeps rules in a config file. A forbidden rule has a name, a severity, and a from and to that match module paths with regular expressions.
// .dependency-cruiser.cjs
module.exports = {
forbidden: [
{
name: "ui-not-to-db",
comment: "UI code goes through the service layer, never straight to the database.",
severity: "error",
from: { path: "^src/ui" },
to: { path: "^src/db" },
},
],
};
npx depcruise src --config .dependency-cruiser.cjs
Severity decides the outcome. error makes the run fail, while warn and info only report. A rule left at warn will report the problem and still let CI pass. madge vs dependency-cruiser covers that difference in detail.
Nx module boundaries (TypeScript monorepos)
In an Nx workspace, you tag each project and let the @nx/enforce-module-boundaries ESLint rule restrict which tags may depend on which. Tags live in each project's project.json:
{ "tags": ["scope:client"] }
// eslint.config.mjs
{
rules: {
"@nx/enforce-module-boundaries": [
"error",
{
depConstraints: [
{ sourceTag: "scope:shared", onlyDependOnLibsWithTags: ["scope:shared"] },
{ sourceTag: "scope:client", onlyDependOnLibsWithTags: ["scope:shared", "scope:client"] },
],
},
],
},
}
A scope:client project that imports a scope:admin library now fails lint. Outside Nx, eslint-plugin-boundaries offers a similar element-based model. Its rule options have changed between releases, so copy the config from its README for the version you install.
import-linter (Python)
import-linter reads contracts from a .importlinter file (or setup.cfg or pyproject.toml). The layers contract lists packages from higher to lower level, and a lower layer may not import a higher one.
[importlinter]
root_package = mypackage
[importlinter:contract:layers]
name = My layers contract
type = layers
layers =
mypackage.high
mypackage.medium
mypackage.low
lint-imports
There is also a forbidden contract type for the "this package must never import that one" case, and lint-imports fails when a contract breaks. Its cycle checks are covered in finding circular dependencies in a monorepo.
go-arch-lint (Go)
go-arch-lint reads .go-arch-lint.yml. Components are folders under a workdir, and deps lists what each may depend on.
version: 3
workdir: internal
components:
handler: { in: handlers/* }
service: { in: services/** }
repository: { in: domain/*/repository }
model: { in: models }
commonComponents:
- models
deps:
handler:
mayDependOn:
- service
service:
mayDependOn:
- repository
go-arch-lint check --project-path .
It returns status code 0 for a clean project and 1 when it finds violations. Go already refuses import cycles between packages, so what you add here is direction. The depguard linter in golangci-lint covers the simpler "this package may not import that one" case if you want one fewer config file.
The tools side by side
| Tool | Language | Rules live in | Rule style | Fails CI how |
|---|---|---|---|---|
| ArchUnit | Java, JVM languages | Java test code | Fluent API, layered architecture helper | Failing JUnit test |
| ArchUnitNET | C# and .NET | Test code | Fluent API over loaded assemblies | Failing xUnit, NUnit or MSTest test |
| dependency-cruiser | JavaScript, TypeScript | .dependency-cruiser.cjs | forbidden rules with path regexes | Failure on error severity |
| Nx module boundaries | TypeScript monorepos | ESLint config plus project tags | Tag constraints | ESLint error |
| import-linter | Python | .importlinter | Contracts: layers, forbidden | lint-imports failure |
| go-arch-lint | Go | .go-arch-lint.yml | Components and mayDependOn lists | Exit code 1 |
Scroll the table sideways to see every column.
Pick by language first. Inside one language the real difference is where the rules live: in test code you can refactor (ArchUnit, ArchUnitNET), or in a config file anyone can read (the rest). Architecture as code means the same thing either way: the rules are versioned next to the code they govern and reviewed in the same pull request.
Running architecture tests in CI
Treat an architecture check as a required step, the same as lint. Three habits matter more than the choice of tool.
- Start with the rules you already believe. Write the layers you would draw on a whiteboard. If the first run reports 400 violations, freeze them. Most tools can record a baseline (dependency-cruiser has
--ignore-known, ArchUnit hasFreezingArchRule), so the build fails only on new violations and you pay the old ones down over time. - Run on the pull request, not nightly. The value is the feedback to the author who just added the import.
- Make failures say why. Fill in the
comment,nameorbecausefield. A rule calledui-not-to-dbwith a sentence about the layering gets fixed. An anonymous red build gets disabled.
# .github/workflows/architecture.yml
name: architecture
on: pull_request
jobs:
rules:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 22 }
- run: npm ci
- run: npx depcruise src --config .dependency-cruiser.cjs
Swap the last step for lint-imports, go-arch-lint check or your build tool's test task.
What import rules cannot see
Import-rule tools answer one question: does this edge point the allowed way? That is worth enforcing, and it leaves three gaps.
Cycles that grow slowly
A layer rule that lets A import B says nothing about whether B reaches back to A through three other modules. Each edge is legal and the loop is the problem. Cycle detection runs over the whole graph, and the fix is usually to cut one specific edge, which is a different job from writing a rule. The coupling and cohesion guide explains why tangled modules cost so much to change.
Decisions the code drifts from
Teams record why they chose a structure: use the outbox pattern, never call billing synchronously, keep this module free of framework imports. An architecture decision record captures that, but a document stops nobody. When the code moves on and the record does not, the next engineer reads a decision that is no longer true, or breaks one without knowing it exists. repowise ties decisions to the files they govern and flags the ones that have gone stale or are contradicted (see decisions). That is a different signal from an import edge.
Changes that deserve a higher bar
Not every component needs the same scrutiny. A change to the payments module with no tests should not be treated like a change to an internal admin script, and no layering rule expresses that. It is a policy question: which components, which evidence, which consequence.
Where repowise fits
repowise complements the tools above. They enforce import direction; its change policy works on the evidence around a change.
Rules live in .repowise/policies.yaml, next to the code they govern. A rule selects components by name, tag or criticality, then tests conditions over the change's evidence: reaching tests, contract breaks, decisions crossed and bus factor. It can also wrap an existing gate such as security, coverage, doc_drift or health.
version: 1
rules:
- name: payments-need-tests
match:
components: {tags: [pci]}
when:
reaching_tests: missing
action: require_tests
- name: no-silent-contract-breaks
when:
contract_break: true
action: fail
repowise check evaluates the rules against a revision range, locally or in CI:
repowise check main..HEAD
repowise check main..HEAD --sarif-file policy.sarif --junit-file policy.xml
The actions are warn, require_owner_review, require_tests and fail. Only fail exits 1; the others are reported in every format. SARIF 2.1.0 feeds GitHub code scanning or reviewdog, and JUnit shows up in any CI test view, so it slots in beside the import-rule step above. A condition whose evidence is not available, for example when there is no index, is reported as not evaluated and never fires.
Cycles come from the graph. repowise finds them over runtime imports, and its Break Cycle plan names the smallest set of import edges to invert. The architecture feature page shows the graph and components, and the code quality hub links the rest of the code-health topics.
FAQ
- What is an ArchUnit?
- ArchUnit is an open-source Java library for testing architecture. You write rules as Java code, for example that nothing may access the
controllerlayer, and run them with JUnit. A violation fails the test, so the build breaks. The same company publishes ArchUnitNET for .NET. - What is architecture testing?
- Architecture testing is writing automated tests that check structural rules about code: which layers may depend on which, which modules are off limits, whether cycles exist. The tests read the dependency graph statically and run in CI, so a violation shows up on the pull request that introduced it.
- What are architecture fitness functions?
- A fitness function is an automated check that measures how well a system meets an architectural goal. The term comes from the book Building Evolutionary Architectures. Dependency rules are the structural kind. Others measure performance, security or build time.
- Is there an ArchUnit for Python, JavaScript or Go?
- Yes, under other names. import-linter does layer and forbidden contracts in Python, dependency-cruiser and Nx module boundaries cover JavaScript and TypeScript, and go-arch-lint covers Go. Each has a config or test file that fails CI on a violation.
- How do I add architecture tests to a legacy codebase?
- Write the rules you want, run them once, and freeze the existing violations in a baseline so only new ones fail the build. Then remove entries from the baseline as you fix them. Starting from zero violations on an old codebase usually means the rules get disabled.
- Do architecture tests replace code review?
- No. They automate the mechanical part of review, the direction of an import, so reviewers can spend their time on design questions a rule cannot express.



