Video in progress

Staff 🧪 Testing

How do you use tests to protect architecture rules (layers, module boundaries) from eroding over time?

With a tool like ArchUnit I write the architecture rules as ordinary JUnit tests: controllers must not touch the repository directly, the domain package must not depend on Spring, modules talk only through their public API. They run on every build and catch violations that slipped past review.

📖 Answer

The architecture is written in a document, but nothing enforces it. A year later the billing package imports catalog's internal repository because "it was faster". Each individual violation is small; together they make a monolith where you can't separate a module.

@AnalyzeClasses(packages = "uz.javaintervyu")
class ArchitectureTest {

    @ArchTest
    static final ArchRule controllersDoNotTouchRepositories =
        noClasses().that().resideInAPackage("..web..")
            .should().dependOnClassesThat().resideInAPackage("..repository..");

    @ArchTest
    static final ArchRule modulesTalkThroughApi =
        classes().that().resideInAPackage("..billing.internal..")
            .should().onlyBeAccessed().byClassesThat().resideInAPackage("..billing..");

    @ArchTest
    static final ArchRule noCycles =
        slices().matching("uz.javaintervyu.(*)..").should().beFreeOfCycles();
}

If you use Spring Modulith, ApplicationModules.of(App.class).verify() checks the module boundaries itself and also generates documentation.

A problem when you introduce it to an existing codebase: the first run turns up hundreds of violations. Waiting to fix them all means the rule never gets switched on. ArchUnit's FreezingArchRule "freezes" the current violations: the old ones are recorded and stay quiet, while new ones fail the build. Then the old ones are fixed gradually.

At the organization level, the general rules (for example, "no framework other than jakarta.persistence in the domain package", "nobody uses System.out") go into the test library, while service-specific boundaries stay in each service.

Agree on a rule with the team before writing it: a rule nobody explained gets switched off with @ArchIgnore at the first hard case.