ArchUnit 规则否定包访问?

ArchUnit rule to negate package access?

我偶然发现了以下片段。

ArchRule myRule = classes()
    .that().resideInAPackage("..core..")
    .should().onlyBeAccessed().byAnyPackage("..controller..");

我想知道如何否定这种情况,测试应该检查 core 包是否未被 controller 包访问?

您可以使用 ClassesShould.accessClassesThat(),这(正如它的 JavaDoc 所建议的那样)通常以否定的方式更有意义:

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
// ...

  noClasses()
      .that().resideInAPackage("..controller..")
      .should().accessClassesThat().resideInAPackage("..core..");

您也可以坚持使用 classes() 并使用 GivenClasses.should(…) or GivenClassesConjunction.should(…) with a flexible ArchCondition. For your case, it can be easily composed from pre-defined conditions and predicates:

import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
import static com.tngtech.archunit.lang.conditions.ArchConditions.accessClassesThat;
import static com.tngtech.archunit.lang.conditions.ArchConditions.not;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
// ...

    classes()
        .that().resideInAPackage("..controller..")
        .should(not(accessClassesThat(resideInAPackage("..core.."))));