In this article, we’ll show how to check the architecture of a system using ArchUnit.
2. What Is ArchUnit?
The link between architecture traits and maintainability is a well-studied topic in the software industry. Defining a sound architecture for our systems is not enough, though. We need to verify that the code implemented adheres to it.
Simply put, ArchUnit is a test library that allows us to verify that an application adheres to a given set of architectural rules. But, what is an architectural rule? Even more, what do we mean by architecture in this context?
Let’s start with the latter. Here, we use the term architecture to refer to the way we organize the different classes in our application into packages.
The architecture of a system also defines how packages or groups of packages – also known as layers – interact. In more practical terms, it defines whether code in a given package can call a method in a class belonging to another one. For instance, let’s suppose that our application’s architecture contains three layers: presentation, service, and persistence.
One way to visualize how those layers interact is by using a UML package diagram with a package representing each layer:
Just by looking at this diagram, we can figure out some rules:
- Presentation classes should only depend on service classes
- Service classes should only depend on persistence classes
- Persistence classes should not depend on anyone else
Looking at those rules, we can now go back and answer our original question. In this context, an architectural rule is an assertion about the way our application classes interact with each other.
So now, how do we check that our implementation observes those rules? Here is where ArchUnit comes in. It allows us to express our architectural constraints using a fluent API and validate them alongside other tests during a regular build.
3. ArchUnit Project Setup
<dependency> <groupId>com.tngtech.archunit</groupId> <artifactId>archunit-junit4</artifactId> <version>0.14.1</version> <scope>test</scope> </dependency>
As its artifactId implies, this dependency is specific for the JUnit 4 framework.
There’s also an archunit-junit5 dependency if we are using JUnit 5:
<dependency> <groupId>com.tngtech.archunit</groupId> <artifactId>archunit-junit5</artifactId> <version>0.14.1</version> <scope>test</scope> </dependency>
4. Writing ArchUnit Tests
Once we’ve added the appropriate dependency to our project, let’s start writing our architecture tests. Our test application will be a simple SpringBoot REST application that queries Smurfs. For simplicity, this test application only contains the Controller, Service, and Repository classes.
We want to verify that this application complies with the rules we’ve mentioned before. So, let’s start with a simple test for the “presentation classes should only depend on service classes” rule.
4.1. Our First Test
The first step is to create a set of Java classes that will be checked for rules violations. We do this by instantiating the ClassFileImporter class and then using one of its importXXX() methods:
JavaClasses jc = new ClassFileImporter() .importPackages("com.baeldung.archunit.smurfs");
In this case, the JavaClasses instance contains all classes from our main application package and its sub-packages. We can think of this object as being analogous to a typical test subject used in regular unit tests, as it will be the target for rule evaluations.
Architectural rules use one of the static methods from the ArchRuleDefinition class as the starting point for its fluent API calls. Let’s try to implement the first rule defined above using this API. We’ll use the classes() method as our anchor and add additional constraints from there:
ArchRule r1 = classes() .that().resideInAPackage("..presentation..") .should().onlyDependOnClassesThat() .resideInAPackage("..service.."); r1.check(jc);
Notice that we need to call the check() method of the rule we’ve created to run the check. This method takes a JavaClasses object and will throw an exception if there’s a violation.
This all looks good, but we’ll get a list of errors if we try to run it against our code:
java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'classes that reside in a package '..presentation..' should only depend on classes that reside in a package '..service..'' was violated (6 times): ... error list omitted
Why? The main problem with this rule is the onlyDependsOnClassesThat(). Despite what we’ve put in the package diagram, our actual implementation has dependencies on JVM and Spring framework classes, hence the error.
4.2. Rewriting Our First Test
One way to solve this error is to add a clause that takes into account those additional dependencies:
ArchRule r1 = classes() .that().resideInAPackage("..presentation..") .should().onlyDependOnClassesThat() .resideInAPackage("..service..", "java..", "javax..", "org.springframework..");
With this change, our check will stop failing. This approach, however, suffers from maintainability issues and feels a bit hacky. We can avoid those issues rewriting our rule using the noClasses() static method as our starting point:
ArchRule r1 = noClasses() .that().resideInAPackage("..presentation..") .should().dependOnClassesThat() .resideInAPackage("..persistence..");
Of course, we can also point that this approach is deny-based instead of the allow-based one we had before. The critical point is that whatever approach we choose, ArchUnit will usually be flexible enough to express our rules.
5. Using the Library API
ArchUnit makes the creation of complex architectural rules an easy task thanks to its built-in rules. Those, in turn, can also be combined, allowing us to create rules using a higher level of abstraction. Out of the box, ArchUnit offers the Library API, a collection of prepackaged rules that address common architecture concerns:
- Architectures: Support for layered and onion (a.k.a. Hexagonal or “ports and adapters”) architectures rule checks
- Slices: Used to detect circular dependencies, or “cycles”
- General: Collection of rules related to best coding practices such as logging, use of exceptions, etc.
- PlantUML: Checks whether our code base adheres to a given UML model
- Freeze Arch Rules: Save violations for later use, allowing to report only new ones. Particularly useful to manage technical debts
Covering all those rules is out of scope for this introduction, but let’s take a look at the Architecture rule package. In particular, let’s rewrite the rules in the previous section using the layered architecture rules. Using these rules requires two steps: first, we define the layers of our application. Then, we define which layer accesses are allowed:
LayeredArchitecture arch = layeredArchitecture() // Define layers .layer("Presentation").definedBy("..presentation..") .layer("Service").definedBy("..service..") .layer("Persistence").definedBy("..persistence..") // Add constraints .whereLayer("Presentation").mayNotBeAccessedByAnyLayer() .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation") .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service"); arch.check(jc);
Here, layeredArchitecture() is a static method from the Architectures class. When invoked, it returns a new LayeredArchitecture object, which we then use to define names layers and assertions regarding their dependencies. This object implements the ArchRule interface so that we can use it just like any other rule.
The cool thing about this particular API is that it allows us to create in just a few lines of code rules that would otherwise require us to combine multiple individual rules.
In this article, we’ve explored the basics of using ArchUnit in our projects. Adopting this tool is a relatively simple task that can have a positive impact on overall quality and reduce maintenance costs in the long run.
As usual, all code is available over on GitHub.