ArchUnit
Let’s talk architecture today.
ArchUnit is a test framework to test an application architecture.
It is an interesting concept that I wanted to try out for a while. So I did a little experiment on a Swing application I had.
It looks like unit tests with a fluent interface. It’s quite nice to use. I used Junit 5.
My two rules were simple:
- Backend should not use Frontend classes
- Backend should not use Swing or AWT classes
Using ArchUnit, it looks like this (in Kotlin):
@AnalyzeClasses(packages = ["pro.tremblay.myapp.."])
internal class BackendSegregationTest {
@ArchTest
val backend_doesnt_use_frontend = layeredArchitecture()
.layer("backend").definedBy("pro.tremblay.myapp.backend..")
.layer("frontend").definedBy("pro.tremblay.myapp.frontend..")
.layer("app").definedBy("pro.tremblay.myapp")
.whereLayer("frontend").mayOnlyBeAccessedByLayers("app")
@ArchTest
val no_ui_framework_on_backend = noClasses().that().resideInAPackage("pro.tremblay.myapp.backend..")
.should().accessClassesThat().resideInAnyPackage("javax.swing..", "java.awt..");
}
Two simple rules.
- One is defining my layers and how they should interact.
- The other is telling which packages are forbidden.
Sure enough, the test was failing. I did some refactoring to repair everything and ta-da, for ever after, architecture will be enforced.
You might want to try it out on your own project.
I do recommend it.