← Back to Blog

ArchUnit Tutorial: Turn Java Architecture Rules into Automated Tests

ArchToCode Team October 22, 2026 5 min read
ArchUnit tutorialJava architecture rulesautomated architecture testscode qualityarchitectural consistencyArchToCodecode visualizationMermaid diagramssoftware architecturestatic analysis
Table of contents

Automate Java Architecture Rules with ArchUnit

Maintaining a consistent and clean architecture is crucial for the long-term health of any software project. In Java, tools like ArchUnit empower developers to define and enforce architectural rules as automated tests. This means you can catch architectural violations early in the development cycle, preventing technical debt from accumulating. But what if you could not only test these rules but also visualize your architecture to truly understand the impact of your changes? That's where ArchToCode comes in.

This tutorial will guide you through setting up ArchUnit in your Java project and writing your first architectural tests. We'll then explore how ArchToCode can complement your ArchUnit efforts by providing AI-powered code visualization, helping you understand complex code structures and ensuring your architecture remains robust and understandable.

What is ArchUnit?

ArchUnit is a free, simple, and extensible library for checking the architecture of your Java code with any plain Java unit testing framework. It allows you to define architectural rules (e.g., "classes in the 'controller' package should not access classes in the 'dao' package") and then run these rules as part of your build process. This ensures that your codebase adheres to your defined architectural principles, even as it evolves.

Setting Up ArchUnit in Your Java Project

First, let's add ArchUnit to your project. If you're using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>com.tngtech.archunit</groupId>
    <artifactId>archunit-junit5-api</artifactId>
    <version>1.2.0</version> <!-- Use the latest version -->
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.tngtech.archunit</groupId>
    <artifactId>archunit-junit5-engine</artifactId>
    <version>1.2.0</version> <!-- Use the latest version -->
    <scope>test</scope>
</dependency>

For Gradle, add this to your build.gradle:

testImplementation 'com.tngtech.archunit:archunit-junit5-api:1.2.0'
testRuntimeOnly 'com.tngtech.archunit:archunit-junit5-engine:1.2.0'

Writing Your First ArchUnit Test

Let's imagine a simple layered architecture: controller, service, and repository packages. We want to enforce that controllers can only access services, and services can only access repositories (and other services).

Create a new JUnit 5 test class, for example, ArchitectureTest.java:

package com.archtocode.demo;

import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;

@AnalyzeClasses(packages = "com.archtocode.demo", importOptions = ImportOption.DoNotIncludeTests.class)
public class ArchitectureTest {

    @ArchTest
    static final ArchRule layer_dependencies_are_respected = layeredArchitecture()
        .layer("Controllers").definedBy("..controller..")
        .layer("Services").definedBy("..service..")
        .layer("Repositories").definedBy("..repository..")

        .whereLayer("Controllers").mayOnlyAccessLayers("Services", "Repositories") // Controllers can access services and repositories directly for simplicity, adjust as needed
        .whereLayer("Services").mayOnlyAccessLayers("Repositories")
        .whereLayer("Repositories").mayNotBeAccessedByAnyLayer();

    @ArchTest
    static final ArchRule no_cycles_in_packages = classes().should().beFreeOfCycles();

    @ArchTest
    static final ArchRule service_classes_should_be_named_service = classes()
        .that().resideInAPackage("..service..")
        .should().haveSimpleNameEndingWith("Service");

    @ArchTest
    static final ArchRule repository_classes_should_be_named_repository = classes()
        .that().resideInAPackage("..repository..")
        .should().haveSimpleNameEndingWith("Repository");

    @ArchTest
    static final ArchRule controller_classes_should_be_named_controller = classes()
        .that().resideInAPackage("..controller..")
        .should().haveSimpleNameEndingWith("Controller");
}

In this example:

  • @AnalyzeClasses tells ArchUnit which packages to scan.

  • layeredArchitecture() defines our architectural layers and their allowed dependencies.

  • no_cycles_in_packages checks for unwanted cyclic dependencies.

  • The last three rules enforce naming conventions for classes within each layer.

Run your tests, and ArchUnit will report any violations. This immediate feedback loop is invaluable for maintaining architectural integrity.

Visualizing Architecture with ArchToCode

While ArchUnit tells you if your architecture is broken, ArchToCode helps you see and understand your architecture. By generating interactive Mermaid diagrams directly from your code, ArchToCode provides a visual representation that complements your automated tests.

Imagine you've just run your ArchUnit tests, and one fails, indicating a controller is directly accessing a repository. With ArchToCode, you can:

  1. Connect Your Repository: ArchToCode seamlessly integrates with GitHub repositories or local folders. Simply connect your project to start analyzing your code.

  2. Generate a Diagram: Use one of ArchToCode's 30+ built-in prompt templates, such as "High-Level Project Flow" or "Component Interaction," to instantly generate a Mermaid diagram. You can even create custom prompts for specific architectural views.

  3. Explore the Codebase Visually: ArchToCode's interactive diagrams allow you to click on nodes (classes, functions, components) to inspect their details and explore their source code. You can "Drill Down" to generate sub-diagrams for specific areas, providing a focused view of the problematic dependency.

  4. Understand Relationships: The "Source Code Explorer" panel intelligently analyzes file relationships, showing direct imports, files that import the selected element, and other references. This is incredibly powerful for tracing unexpected dependencies that ArchUnit might flag.

  5. Get AI-Powered Explanations: ArchToCode can generate a comprehensive, 50+ sentence AI explanation of your diagram, detailing its purpose, key components, data flow, and design patterns. This helps you quickly grasp complex architectures and understand why a rule might be violated.

Benefits of Combining ArchUnit and ArchToCode

Integrating ArchUnit with ArchToCode creates a powerful synergy for architectural governance:

  • Proactive Problem Detection: ArchUnit catches violations automatically, preventing them from being merged into the main codebase.

  • Enhanced Understanding: ArchToCode provides a visual map of your code, making it easier to understand the context of ArchUnit failures and pinpoint the root cause.

  • Faster Debugging: When an ArchUnit test fails, ArchToCode's drill-down and source code exploration features help you quickly navigate to the problematic code and understand the dependency.

  • Improved Communication: Share AI-generated diagrams and explanations with your team to discuss architectural decisions and ensure everyone is aligned.

  • Regression Prevention: ArchUnit ensures new code adheres to existing rules, while ArchToCode helps you visualize the impact of new features on your overall architecture.

  • Onboarding New Developers: New team members can quickly grasp the project's architecture by exploring interactive diagrams and AI explanations, reducing ramp-up time.

Conclusion

Automating architectural rules with ArchUnit is a vital practice for any serious Java project. By integrating this with ArchToCode's AI-powered code visualization, you gain an unparalleled ability to not only enforce your architecture but also to understand, communicate, and evolve it effectively. Stop guessing about your codebase's structure and start seeing it clearly.

Ready to visualize your Java architecture and supercharge your ArchUnit efforts? Try ArchToCode today!

Related posts