如何在 ArchUnit 规则中排除一个类?

Luí*_*res 5 java unit-testing archunit

在 ArchUnit 中为分层架构创建规则时,我不清楚如何排除单个类 (Main)。 基本示例排除了源和目标。

...但我不明白它是如何转换成我的需要的。我只想忽略 Main 。为什么?因为 Main 引用了所有层,因为它将所有依赖项注入到位。

原始代码 与失败的测试一起在我的 GitHub 中。(该项目是一个虚拟项目,因此运行起来很简单;只需克隆它,运行测试并看到一个失败)。

Rol*_*der 8

Consider you have imported all your classes:

JavaClasses classes = new ClassFileImporter().importPackages("org.example");
Run Code Online (Sandbox Code Playgroud)

Then you typically check all these classes against an ArchRule, no matter if it's a class rule or an architecture rule:

ArchRule rule = classes()
    .that().areAnnotatedWith(Service.class)
    .should().haveSimpleNameEndingWith("Service");

rule.check(classes);
Run Code Online (Sandbox Code Playgroud)

To exclude classes from the rule, you could filter classes and pass the filtered JavaClasses to the rule:

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.equivalentTo;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.are;

JavaClasses allExceptMain = classes.that(are(not(equivalentTo(Main.class))));
rule.check(allExceptMain);
Run Code Online (Sandbox Code Playgroud)

To exclude the class Main and all classes that are defined inside of Main (inner classes, anonymous classes, lambdas etc.) you could adjust the filter:

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf;

JavaClasses allExceptMain = classes.that(not(belongToAnyOf(Main.class)));
rule.check(allExceptMain);
Run Code Online (Sandbox Code Playgroud)