ArchUnit 确保注释存在
ArchUnit ensuring annotation presence
给定 ArchUnit 库版本 0.12:
是否可以测试场景 "methods annotated with A
should also be annotated with B
or be declared in a type annotated with B
"?
示例:
A.java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}
B.java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {
}
TestCases.java
public class TestCases {
static class ShouldFail {
@A
public void m() {
}
}
static class ShouldPass {
@A
@B
public void m() {
}
}
@B
static class ShouldPassToo {
@A
public void m() {
}
}
}
我尝试了什么?
我认为 ArchConditions.beDeclaredInClassesThat
可以完成这项工作,所以我准备了以下规则:
MethodsShouldConjunction rule = methods()
.that()
.areAnnotatedWith(A.class)
.should()
.beAnnotatedWith(B.class)
.orShould(beDeclaredInClassesThat(areAnnotatedWith(B.class))); //<-- doesn't compile
...但显然我误解了上述方法的目的。该实用程序的 Javadoc 根本没有帮助。我可以用满足断言 "methods declared in a type annotated with B
"?
的任何有效内容替换最后一行吗
原来我不必要地尝试将参数传递给 orShould
方法。为了实现我的目标,应该使用无参数方法扩展规则:
methods()
.that()
.areAnnotatedWith(A.class)
.should()
.beAnnotatedWith(B.class)
.orShould()
.beDeclaredInClassesThat()
.areAnnotatedWith(B.class);
给定 ArchUnit 库版本 0.12:
是否可以测试场景 "methods annotated with A
should also be annotated with B
or be declared in a type annotated with B
"?
示例:
A.java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
}
B.java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {
}
TestCases.java
public class TestCases {
static class ShouldFail {
@A
public void m() {
}
}
static class ShouldPass {
@A
@B
public void m() {
}
}
@B
static class ShouldPassToo {
@A
public void m() {
}
}
}
我尝试了什么?
我认为 ArchConditions.beDeclaredInClassesThat
可以完成这项工作,所以我准备了以下规则:
MethodsShouldConjunction rule = methods()
.that()
.areAnnotatedWith(A.class)
.should()
.beAnnotatedWith(B.class)
.orShould(beDeclaredInClassesThat(areAnnotatedWith(B.class))); //<-- doesn't compile
...但显然我误解了上述方法的目的。该实用程序的 Javadoc 根本没有帮助。我可以用满足断言 "methods declared in a type annotated with B
"?
原来我不必要地尝试将参数传递给 orShould
方法。为了实现我的目标,应该使用无参数方法扩展规则:
methods()
.that()
.areAnnotatedWith(A.class)
.should()
.beAnnotatedWith(B.class)
.orShould()
.beDeclaredInClassesThat()
.areAnnotatedWith(B.class);