Enforce the Architecture¶
Exposing Dependency Problems¶
Accidentally introducing dependencies that go against the Hexagonal Architecture guideline of Dependencies Point Inward can happen without being noticed. The ArchUnit testing library can bring those problems to light.
Tip
Reference documentation for ArchUnit is here.
ArchUnit Dependency
You should already have the ArchUnit dependency in your Maven pom.xml
file. If not, you can add the following dependency and refresh the Maven imports:
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
Goal¶
Use ArchUnit to detect architectural (design) problems in the project. Make changes and see how dependencies going in the wrong direction causes ArchUnit tests to fail.
A. Add ArchUnit Test¶
Create a new test class named HexArchTest
and add the following test code into it:
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchRule;
import org.junit.jupiter.api.Test;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
class HexArchTest {
@Test
void domainMustNotDependOnAdapter() {
JavaClasses importedClasses =
new ClassFileImporter().importPackages("com.jitterted.ebp.blackjack");
ArchRule myRule = noClasses().that().resideInAPackage("..domain..")
.should().dependOnClassesThat()
.resideInAPackage("..adapter..");
myRule.check(importedClasses);
}
}
Run this test, and you may find that it fails. See if you can figure out why and how to fix it.
B. Break the Dependency Direction¶
Force the test to fail in the domain code:
- Go into the constructor of a domain class, and instantiate one of the DTOs.
- Run the
HexArchTest
: what happens?
You are done!