DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Dependency Injection
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Trending

  • Why AI-Generated Code Breaks Your Testing Assumptions
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • S3 Vectors: How to Build a RAG Without a Vector Database
  1. DZone
  2. Coding
  3. Java
  4. Introducing Coding Constraints Using ArchUnit

Introducing Coding Constraints Using ArchUnit

Introduce certain design/coding level constraints to developers while implementing the functionalities with ArchUnit.

By 
Pravin Tarte user avatar
Pravin Tarte
·
May. 20, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

How often have you experienced a well-defined and understood software architecture on paper, but then it falls apart when developers start implementing it?

Recently, while re-architecting legacy components in an application, I experienced the same. As more and more developers joined the team, it became a constant routine to make them aware of the design thought adopted in the architecture and how to adhere to it. 

I know some of you may say, "Why not control the implementation during code-review?" Well technically you can, but in that case, the reviewer becomes the bottleneck in the whole SDLC process. 

What if there was something that could enforce the design constraint in the form of the test cases, and should there be a violation of the agreed-upon design principle, to mark the build as failed? 

My quest led me to a test library called ArchUnit. 

ArchUnit is a test library that allows us to validate whether an application adheres to a given set of design consideration or architecture rules. 

But, what all things constitute under design and architecture, well it can be anything of below:

  • Field/Class/Method Naming convention
  • Class dependency on other packages
  • Class polymorphism design rules
  • Checking existence of cyclic dependencies in the code
  • Enforcing Layered or Onion architecture 

ArchUnit has excellent integration with the other testing frameworks like JUnit, TestNg. ArchUnit tests get executed as part of regular unit test cases in a CI/CD pipeline, so feedback is immediate. 

Enough of theory, let's see how you can implement these.

ArchUnit has excellent integration with JUnit, so all you have to do is add the below dependency in your java maven pom file.

If you are using JUnit 5, add the below dependency:

Java
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>com.tngtech.archunit</groupId>
3
    <artifactId>archunit-junit5</artifactId>
4
    <version>0.18.0</version>
5
    <scope>test</scope>
6
</dependency>



If you are still stuck in the dark ages, this is for JUnit 4:

Java
 




x



1
<dependency>
2
    <groupId>com.tngtech.archunit</groupId>
3
    <artifactId>archunit-junit4</artifactId>
4
    <version>0.14.1</version>
5
    <scope>test</scope>
6
</dependency>



Let's write some tests.

If you are a seasoned developer, you might have guessed by now that ArchUnit works on the Java reflection. So it is imperative to control how many classes within the entire project should be analyzed for this rule. 

This is achieved as below. Consider this a prerequisite for writing the tests.

Java
 




xxxxxxxxxx
1


 
1
@AnalyzeClasses(packages = "com.archunit",
2
        importOptions = {ImportOption.DoNotIncludeTests.class, ImportOption.DoNotIncludeJars.class})
3
// Analysing the classes defined in the com.archunit package and ignoring jar and test classes
4
public class CodingRulesTests {
5
  
6
}



  • Let's enforce some naming convention
    • Let's take an example of enforcing the coding standard on how to define logger    
    • Second example is of standards around defining Util class and its methods
Java
 




xxxxxxxxxx
1


 
1
@ArchTest
2
static final ArchRule loggers_should_be_private_static_final =
3
fields().that().haveRawType(Logger.class)
4
          .should().beStatic()
5
          .andShould().bePrivate().
6
           andShould().beFinal().
7
           because("It's our team's agreed convention");


Java
 




xxxxxxxxxx
1


 
1
@ArchTest
2
static final ArchRule utility_methods_should_be_public_static = 
3
            methods().that().areDeclaredInClassesThat().
4
            resideInAnyPackage("..util..").
5
            should().bePublic().
6
            andShould().beStatic();


         

  • There are certain general coding rules/conventions defined in the ArchUnit itself. We can chain them together using CompositeArchRule.
Java
 




xxxxxxxxxx
1
12


 
1
// Classes should not access System.in , System.out or System.err
2
// Classes should not use java util logging
3
// Classes should not use joda time
4
// Methods should not throw generic exception
5
// For spring classes, there should be any field injection (@Autowired), use constrctor injection
6
@ArchTest
7
static final ArchRule implement_general_coding_practices =          CompositeArchRule.of(GeneralCodingRules.NO_CLASSES_SHOULD_ACCESS_STANDARD_STREAMS)
8
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_THROW_GENERIC_EXCEPTIONS)
9
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JAVA_UTIL_LOGGING)
10
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_JODATIME)
11
            .and(GeneralCodingRules.NO_CLASSES_SHOULD_USE_FIELD_INJECTION)
12
            .because("These are Voilation of general coding rules");



  • If the standard ArchUnit Java API methods are not sufficient for enforcing the conditions, users can create a custom ArchCondition and use it in the ArchRule.
Java
 




x
18


 
1
// Below Arch Condition enforcing the standard for defining the rest endpoint. Asking to put root as archUnit
2
static final ArchCondition<JavaClass> have_top_level_request_mapping_annotation_should_have_archUnit_as_base =
3
new ArchCondition<JavaClass>("Fld annotated with @RequestMapping shld contain archUnit") {
4
    @Override
5
   public void check(JavaClass javaClass, ConditionEvents conditionEvents) {
6
   String[] values = javaClass.getAnnotationOfType(RequestMapping.class).value();
7
     boolean result = Arrays.stream(values).anyMatch(v -> v.contains("archUnit"));
8
     if (!result) {
9
         conditionEvents.add(SimpleConditionEvent.violated(javaClass,
10
                 javaClass.getSimpleName() + " Rest Controller don't have archUnit in Request mapping "));
11
                    }
12
                }
13
            };
14

          
15

          
16
static ArchRule enforce_rest_controller_standards =
17
            classes().that().resideInAnyPackage("..controller..").and()
18
            .areAnnotatedWith(RestController.class).                   should(have_top_level_request_mapping_annotation_should_have_archUnit_as_base);



  • You can also enforce layered or onion architecture rules
Java
 




x


 
1
LayeredArchitecture arch = layeredArchitecture()
2
   // Define layers within the project
3
  .layer("Controller").definedBy("..controller..")
4
  .layer("Service").definedBy("..service..")
5
  .layer("Persistence").definedBy("..persistence..")
6
  // Add dependency constraints
7
  .whereLayer("Controller").mayNotBeAccessedByAnyLayer()
8
  .whereLayer("Service").mayOnlyBeAccessedByLayers("Presentation")
9
  .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");
10

          



Known Limitations

  • ArchUnit cannot analyze the annotations marked with Retention.SOURCE , typical examples are Lombok annotations.

I hope you have gained something new from this article. 

If you are curious to find out more about the ArchUnit?  Do visit their user guide and examples. 

Coding (social sciences) unit test Java (programming language) Software architecture

Opinions expressed by DZone contributors are their own.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Dependency Injection
  • Mastering Unit Testing and Test-Driven Development in Java
  • Comprehensive Guide to Unit Testing Spring AOP Aspects

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook