Skip to content

7. 6 -Lab 4 Exploring ArchUnit

In this lab we will explore ArchUnit and include more architecture rules exploring the use of ArchUnit.

7.1 Step 1: Include ArchUnit in the project

At the ´pom.xml` file, include righ after the version tag the following:

<properties>
    <jmolecules.version>1.9.0</jmolecules.version>
</properties>

At the ´pom.xml` file, at the dependencies section, add the following dependency:

<dependency>
    <groupId>org.jmolecules</groupId>
    <artifactId>jmolecules-ddd</artifactId>
    <version>${jmolecules.version}</version>
</dependency>
<dependency>
    <groupId>org.jmolecules</groupId>
    <artifactId>jmolecules-layered-architecture</artifactId>
    <version>${jmolecules.version}</version>
</dependency>
<dependency>
    <groupId>org.jmolecules.integrations</groupId>
    <artifactId>jmolecules-archunit</artifactId>
    <version>0.28.0</version>
    <scope>test</scope>
</dependency>

7.2 Step 2: Create a new rule

Create a new class at the src/test/java/com/example/ folder named ArchitectureTest.java with the following content:

package com.example.ecommerce;

import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition;
import org.junit.jupiter.api.Test;

public class ArchitectureTest
{
    @Test
    void domainClassesShouldNotDependOnApplicationLayer() {
        String packageName = SimpleGreetResource.class.getPackageName();
        JavaClasses importedClasses = new ClassFileImporter().importPackages(packageName);

        ArchRuleDefinition.noClasses()
                .that().resideInAPackage(packageName)
                .should().dependOnClassesThat().resideInAPackage("..application..")
                .check(importedClasses);
    }
}
package com.example.ecommerce;


import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import org.jmolecules.archunit.JMoleculesArchitectureRules;
import org.jmolecules.archunit.JMoleculesDddRules;
import org.junit.jupiter.api.Test;

public class JMoleculesDddUnitTest {

    @Test
    void checkTheLayerIntegration() {
        String packageName = SimpleGreetResource.class.getPackageName();
        JavaClasses classes = new ClassFileImporter().importPackages(packageName);
        JMoleculesArchitectureRules.ensureLayering().check(classes);

    }

    @Test
    void checkDDDIntegration() {
        String packageName = SimpleGreetResource.class.getPackageName();
        JavaClasses classes = new ClassFileImporter().importPackages(packageName);
        JMoleculesDddRules.all().check(classes);
    }
}

7.3 Step 3: Run the tests

Run the tests and check the results. Also, please, explore both ArchUnit rules and the JMolecules rules:


Last update: 2025-09-05