使用 ArchUnit 进行检查和断言来确保使用了正确的 AssertJ 语句。
以下是一个示例代码,演示如何使用 ArchUnit 来检查并确保使用了一些具有断言的 AssertJ 语句:
@Test
public void testAssertions() {
JavaClasses classes = new ClassFileImporter().importPackages("com.example");
ArchRule rule = classes.should()
.accessClassesThat()
.resideInAnyPackage("com.example")
.andShould()
.callMethodWhere(new com.tngtech.archunit.core.domain.JavaMethod.Functions.Get() {
@Override
public CodeLocation apply(JavaCodeUnit input) {
return input.getOrigin().getLocation();
}
})
.that()
.haveNameMatching("assert.*")
.should()
.beAnnotatedWith(Assertions.class);
rule.check(classes);
}
这个示例代码假设测试的代码包为“com.example”,并使用 ArchUnit 的 should() 方法来断言包中的所有类都使用了带有断言的 AssertJ 语句。should() 方法在链式调用中允许添加其它的约束条件,例如,accessClassesThat() 和 callMethodWhere() 方法以及 haveNameMatching() 和 beAnnotatedWith() 方法,用于在访问类和调用方法时添加约束限制。
最后,通过调用 check() 方法来检查所有的断言是否都被正确地使用了。如果任何一条规则不符合规范,就会抛出异常并指出错误的位置。