Quick revision
The short answer
The rule is noClasses().that().resideInAPackage("..web..").should().accessClassesThat().resideInAPackage("..repository.."). We declare it as a static field annotated @ArchTest in a class annotated @AnalyzeClasses(packages = "com.example"), and it runs as a normal JUnit test against the compiled classes. For a full set of layer rules, layeredArchitecture() expresses them all in one place.
What to remember
In this answer, we wrote the rule noClasses().that().resideInAPackage("..web..").should().accessClassesThat().resideInAPackage("..repository.."), ran it with @AnalyzeClasses and an @ArchTest field, and saw the failure message that names the exact call. Because ArchUnit checks compiled bytecode, it runs as a normal unit test, and layeredArchitecture() lets us express all the layer rules together.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The rule is noClasses().that().resideInAPackage("..web..").should().accessClassesThat().resideInAPackage("..repository.."). We declare it as a static field annotated @ArchTest in a class annotated @AnalyzeClasses(packages = "com.example"), and it runs as a normal JUnit test against the compiled classes. For a full set of layer rules, layeredArchitecture() expresses them all in one place.
Why this question is asked
Every Spring application starts with a clean picture: controllers call services, services call repositories. A year later, someone injects a repository into a controller to save time, and the picture quietly stops being true. Code review misses it because the change looks harmless. ArchUnit lets us write the picture down as a test, so the build fails the moment someone breaks it. Interviewers ask this to see whether we can write such a rule and understand how ArchUnit evaluates it. In this answer, we will recap what ArchUnit is, write the rule, run it in JUnit, see the failure it produces, and then express the same idea with layeredArchitecture().
1A Quick Recap of ArchUnit
ArchUnit is a Java library for testing architecture. It imports our compiled classes, reads their bytecode, and builds a model of every class, method, field and dependency between them. We then write rules in a fluent Java API that reads almost like an English sentence, and ArchUnit checks them against that model.
Because it works on compiled bytecode, ArchUnit needs no special build step and no running application. It is just a library on the test classpath, and its rules run as ordinary unit tests with JUnit. The package patterns use a simple syntax: a double dot means any number of packages, so "..web.." matches com.example.web, com.example.orders.web.dto and any other package with a web segment.
2Writing the Rule
We want a rule that says no class in a web package may access a class in a repository package. Access here means calling a method, reading a field, or calling a constructor.
Notice the structure of the sentence. noClasses() selects what the rule is about, that().resideInAPackage("..web..") narrows it to web classes, and should().accessClassesThat() describes the forbidden relation. The because() clause is optional, but it puts the reason into the failure message, which helps the next developer understand the rule instead of fighting it.
The test class needs the archunit-junit5 dependency (com.tngtech.archunit:archunit-junit5) in test scope. @AnalyzeClasses tells ArchUnit which packages to import, and each static field annotated @ArchTest becomes one test in the JUnit report. ArchUnit caches the imported classes, so several rules in the same class share one import.
3Seeing the Rule Fail
Suppose a controller takes a shortcut and calls the repository directly.
- Import compiled classes
@AnalyzeClasses(packages = "com.example") - Select classes in ..web..
noClasses().that().resideInAPackage - Collect their accessesmethod calls, field reads, constructor calls
- Any target in ..repository..?YesFail with each violation and its lineNoTest passes
4 steps in order. Play them, or step through them one at a time.
ArchUnit reads bytecode, so it sees every call, including ones hidden in lambdas.
The message names the rule, the reason, and the exact method and line that broke it. Notice one subtlety: the constructor parameter and field of type OrderRepository are dependencies, not accesses. If we want to forbid even holding a reference, we use dependOnClassesThat() instead of accessClassesThat(), which also covers field types, parameters, return types and annotations.
4Expressing All Layers With layeredArchitecture()
A single rule is fine, but most applications have several layer rules. Writing each as its own noClasses() rule gets repetitive and leaves gaps. layeredArchitecture() lets us define the layers once and state who may use whom.
This rule forbids web-to-repository access as a consequence of the last line: only the service layer may use repositories. It also catches violations we did not think to write separately, such as a repository calling a service. consideringAllDependencies() controls which dependencies are checked; ArchUnit also offers consideringOnlyDependenciesInLayers(), which ignores dependencies on classes outside the defined layers, such as JDK or Spring classes.
5Follow-up questions
Why test architecture in a unit test instead of a review checklist?
A test runs on every build and never gets tired. A review checklist depends on the reviewer noticing an import among hundreds of changed lines. ArchUnit makes the rule explicit, versioned with the code, and impossible to break silently.
Does ArchUnit slow down the test suite?
Importing classes takes a moment, typically a second or a few seconds for a large application, and ArchUnit caches the import per set of locations, so many rules share it. Excluding test classes with importOptions = ImportOption.DoNotIncludeTests.class on @AnalyzeClasses also keeps the import smaller and avoids false positives from test code.
What if the code already has violations?
We can wrap the rule in FreezingArchRule.freeze(rule). It records the current violations in a store, fails only on new ones, and removes entries as they are fixed, so we can introduce a rule into an existing code base without fixing everything first.
6Conclusion
In this answer, we wrote the rule noClasses().that().resideInAPackage("..web..").should().accessClassesThat().resideInAPackage("..repository.."), ran it with @AnalyzeClasses and an @ArchTest field, and saw the failure message that names the exact call. Because ArchUnit checks compiled bytecode, it runs as a normal unit test, and layeredArchitecture() lets us express all the layer rules together.
Open with
I would write it as an ArchUnit rule in a normal test class. The class is annotated with @AnalyzeClasses with packages equals com.example, which imports all compiled classes under that package.
Then, if they want more
Inside it I declare a static final ArchRule field annotated with @ArchTest: noClasses, that reside in a package matching dot dot web dot dot, should access classes that reside in a package matching dot dot repository dot dot, and I add a because clause so the failure explains the reason.
The double dots match any number of packages, so it catches web packages at any depth. ArchUnit reads the bytecode, so it runs like any other JUnit test, needs only the archunit-junit5 dependency, and the failure lists the exact method and line that made the call.
If I want to forbid even a field or constructor parameter of the repository type, I would use dependOnClassesThat instead of accessClassesThat.
And if the application has several layers, I would rather use layeredArchitecture: define web, service and repository layers by package, then say the repository layer may only be accessed by the service layer, which covers this rule and several others in one place. For existing violations, FreezingArchRule lets me fail only on new ones.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Apache Maven guides, Gradle user manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write an ArchUnit rule that fails if any class in the ..web.. package accesses a class...": https://scrivio-interview-library.netlify.app/java/code-quality-tools/9e1f2aa4fe/