How to enforce a restriction of using Instant.now() or new Date() in any Java Test Methods?

54 Views Asked by At

Want to enforce a restriction of using Instant.now() or new Date() in any Java Method. Below is the sample class

class Demo {

    void methodOne() {
        Date date = new Date();
        // ...
    }

    void methodTwo() {
        Instant instant = Instant.now();
        // ...
    }
}

1

There are 1 best solutions below

4
Manfred On

The following simple ArchRule unconditionally forbids calling these methods:

    @ArchTest
    ArchRule no_direct_date_or_instant_instantiation =
        com.tngtech.archunit.lang.syntax.ArchRuleDefinition
            .noClasses()
            .should().callConstructor(Date.class)
            .orShould().callMethod(Instant.class, "now");

For your Demo class, this gives:

java.lang.AssertionError: Architecture Violation [Priority: MEDIUM] - Rule 'no classes should call constructor Date.() or should call method Instant.now()' was violated (2 times):
Method <Demo.methodOne()> calls constructor <java.util.Date.<init>()> in (SO77127672.java:29)
Method <Demo.methodTwo()> calls method <java.time.Instant.now()> in (SO77127672.java:34)