Search code examples
javajunit5archunit

Ensure no LocalDateTime.now() with no arguments with Archunit, but accept LocalDateTime.now(clock)


I am pretty new to Archunit and I am struggling to find in the docs how to make a rule that allow usage of LocalDateTime.now(clock) but forbids usage of LocalDateTime.now() (no argument)

Any Idea?


Solution

  • Using an IDE with code completion, you can browse the fluent API by starting with noClasses().should().… and looking at the suggestions. (Instead of classes/noClasses, you may also find other ArchRuleDefinitions like fields/noFields or codeUnits/noCodeUnits useful).

    In your case, you might discover callMethod, where the provided method parameter types allow you to distinguish LocalDateTime.now() from LocalDateTime.now(clock):

    @ArchTest
    ArchRule no_LocalDateTime_now_without_clock = com.tngtech.archunit.lang.syntax.ArchRuleDefinition
         .noClasses()
         .should().callMethod(LocalDateTime.class, "now" /* without parameters */)
         .because("we want to use `LocalDateTime.now(clock)` instead");