Spring Boot - Unit Test your project architecture with ArchUnit
Join the DZone community and get the full member experience.Join For Free
When building software, it's common for development teams to define a set of guidelines and code conventions that are considered best practices.
These are practices that are generally documented and communicated to the entire development team that has accepted them. However, during development, developers can violate these guidelines which are discovered during code reviews or with code quality checking tools.
An important aspect is therefore to automate these directives as much as possible over the entire project architecture in order to optimize the reviews.
We can impose these guidelines as verifiable JUnit tests using ArchUnit. It guarantees that a software version will be discontinued if an architectural violation is introduced.
ArchUnit is a free, simple and extensible library for checking the architecture of your Java code using any plain Java unit test framework. That is, ArchUnit can check dependencies between packages and classes, layers and slices, check for cyclic dependencies and more. It does so by analyzing given Java bytecode, importing all classes into a Java code structure.
ArchUnit lets you implement rules for the static properties of application architecture in the form of executable tests such as the following:
- Package dependency checks
- Class dependency checks
- Class and package containment checks
- Inheritance checks
- Annotation checks
- Layer checks
- Cycle checks
ArchUnit’s JUnit 5 support, simply add the following dependency from Maven Central:
Package Dependency Checks
Services and Repositories should not talk to Web layer.
Class Dependency Checks
ArchUnit offers an abstract DSL-like fluent API, which can in turn be evaluated against imported classes. Services should only be accessed by Controllers .
The two dots represent any number of packages (compare AspectJ Pointcuts).
A common rule is the naming convention. for example all service class names must end with Service, Component etc.
The ArchUnit Lang API can define rules for members of Java classes. This may be relevant, for example, if methods in a certain context need to be annotated with a specific annotation, or if return types implement a certain interface.
In Spring Boot app, Service layer depends on Repository layer, Controller layer depend on Service layer.
ArchUnit offers a set of features to assert that your layered architecture is respected. These tests provide automated assurances that access and use is maintained within your defined limits. it is therefore possible to write custom rules. In this article, we have just described a few of the rules. The official ArchUnit guide presents the different possibilities.
The complete source code can be found in my GitHub repository.
Opinions expressed by DZone contributors are their own.