[英]Archunit check method calls
I have a class that has three methods that shouldn't be called from certain classes.我有一个 class,它有三个不应从某些类调用的方法。
How can I check this with Archunit?我怎样才能用 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. method1 和 method2 只能由类 Bar1 和 Bar2 调用。
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;
With和
import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.lang.conditions.ArchConditions.callMethod;
you can use您可以使用
ArchRule rule = noClasses()
.that().doNotHaveFullyQualifiedName(Bar1.class.getName())
.and().doNotHaveFullyQualifiedName(Bar2.class.getName())
// alternative 1:
.should().callMethod(Foo.class, "method1")
.orShould().callMethod(Foo.class, "method2");
// alternative 2:
// .should(callMethod(Foo.class, "method1").or(callMethod(Foo.class, "method2")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.