Search code examples
archunit

Archunit check method calls


I have a class that has three methods that shouldn't be called from certain classes.

How can I check this with Archunit?

So for example

public class Foo {

   public void method1() {
   }

   public void method2() {
   }

   public void method3() {
   }
}

method1 and method2 should only be called by classes Bar1 and Bar2.


Solution

  • I have a very similar requirement and came up with this:

    @ArchTest
        public static final ArchRule rule = noClasses()
                .that(not(name(Bar1.class.getName()))
                              .and(not(name(Bar2.class.getName()))))
                .should().callMethodWhere(target(nameMatching("method1"))
                                                  .and(target(owner(assignableTo(Foo.class)))))
                .orShould().callMethodWhere(target(nameMatching("method2"))
                                                  .and(target(owner(assignableTo(Foo.class)))));
    

    I have not tested it, but should be close I think.

    EDIT: imports are:

    import com.tngtech.archunit.junit.AnalyzeClasses;
    import com.tngtech.archunit.junit.ArchTest;
    import com.tngtech.archunit.lang.ArchRule;
    
    import static com.tngtech.archunit.base.DescribedPredicate.not;
    import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target;
    import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
    import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
    import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.nameMatching;
    import static com.tngtech.archunit.core.domain.properties.HasOwner.Predicates.With.owner;
    import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;