ArchUnit:如何避免对Java类的依赖关系违反

时间:2019-06-03 11:54:07

标签: java archunit

我想验证,给定程序包中的类仅引用驻留在程序包本身中的类。但是我受到侵犯,告诉我a类取决于例如java.lang.String,对我来说完全可以。有没有办法忽略基本的Java包?

        @ArchTest
        static final ArchRule zeroDependencyOfDomain = noClasses().that()
            .resideInAPackage("..domain..")
            .should().dependOnClassesThat()
            .resideOutsideOfPackages("..domain..");

2 个答案:

答案 0 :(得分:0)

您可以显式允许对Java包的依赖:

@ArchTest
static final ArchRule zeroDependencyOfDomain = noClasses().that()
    .resideInAPackage("..domain..")
    .should().dependOnClassesThat()
    .resideOutsideOfPackages("..domain..", "java.(**)");

您还可以使用classes()onlyDependOnClassesThat(),在我看来,这更容易阅读:

@ArchTest
static final ArchRule zeroDependencyOfDomain = classes().that()
    .resideInAPackage("..domain..")
    .should().onlyDependOnClassesThat()
    .resideInAnyPackage("..domain..", "java.(**)");

答案 1 :(得分:0)

类似于其他答案,我还没有找到比这更好的方法了:

private static final String[] COMMON_PACKAGES = {
    "java..",
    "javax..",
    "com.google..",
    "org.springframework.."};

@ArchTest
final ArchRule classesInProdutPackageNoOutsideAccess =
    classes()
        .that()
        .resideInAnyPackage(PACKAGE_FOO)
        .should()
        .onlyAccessClassesThat()
        .resideInAnyPackage(commonPackagesAnd(PACKAGE_FOO));


private static String[] commonPackagesAnd(String... packages) {
    return ArrayUtils.addAll(packages, COMMON_PACKAGES);
}