Try   HackMD

Hello Learners!

We discovered a fascinating library which allows us to test our architecture: ArchUnit

We want to share a few cool use cases for the library. We hope you find them intriguing!

Test Layered Architecture

layeredArchitecture()
    .layer("Controllers").definedBy("io.pivotal.archunitdemo.controller..")
    .layer("Services").definedBy("io.pivotal.archunitdemo.service..")
    .layer("Persistence").definedBy("io.pivotal.archunitdemo.persistence..")

    .whereLayer("Controllers").mayNotBeAccessedByAnyLayer()
    .whereLayer("Services").mayOnlyBeAccessedByLayers("Controllers")
    .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Services")

    .check(classes);

Prevent Cyclic Dependencies

slices()
    .matching("..(domain_package).(*)..").namingSlices("$2 of $1")
    .should().beFreeOfCycles()
    .check(classes)

Note: slices are sets of related packages. For example, the above test will ensure all packages under domain_package are free of cycles.

Introducing New Rules To Existing Codebase

Say you want to specify an architecture rule, but you inherit a legacy codebase which has multiple violations of that rule.

You can record these violations and use FreezingArchRule to disregard past violations and only enforce the rule in the future.

freeze(noClasses().should().dependOnClassesThat().resideInAPackage("..service.."))
    .check(classes)

Prevent calls to System.out.println() and System.err.println()

You can also use ArchUnit as a linter.

noClasses().should(ACCESS_STANDARD_STREAMS).check(classes)

Visualizing Architecture

Do you have a component diagram that you use to communicate your architecture? How up to date is it?

ArchUnit can turn your PlantUML diagrams into tests!

Now you can be confident that your architecture and your diagram are always in sync.

For example, if you have the following architecture diagram:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

then you can ask ArchUnit to run this diagram as a test like so:

val plantUmlDiagram = ArchUnitTest::class.java.getResource("archunit_demo.puml") classes().should(adhereToPlantUmlDiagram(plantUmlDiagram, consideringOnlyDependenciesInDiagram())) .check(classes)

Intrigued?

The above are only a few examples of what you can achieve with ArchUnit.

For more examples, please visit ArchUnit Test Examples and the official docs.

Have a great weekend!