我用自定义注释注释了一些方法:“ExistForTesting”
@Documented
@Target({TYPE, FIELD, METHOD})
@Retention(SOURCE)
public @interface ExistForTesting {
String why() default "";
}
我想编写一个 (Junit5 + ArchUnit) 单元测试,以确保 ExistForTesting 注释方法仅用于单元测试。所以,我写了给定的测试:
ArchCondition<JavaClass> NOT_CALL_TEST_METHODS =
new ArchCondition<JavaClass>("not call methods annotated with ExistForTesting") {
@Override
public void check(@NotNull JavaClass item, ConditionEvents events) {
item.getMethodCallsFromSelf().stream().filter(method -> method.getTarget().isAnnotatedWith(ExistForTesting.class))
.forEach(method -> {
String message = String.format(
"Method %s is annotated with ExistForTesting",
method.getTarget().getFullName());
events.add(SimpleConditionEvent.violated(method, message));
});
}
};
@Test
public void shouldNotUseTestMethods() {
classes().that()
.haveSimpleNameNotEndingWith("Test")
.should(NOT_CALL_TEST_METHODS)
.check(appClasses);
}
问题:未检测到我的注释。
调试器找到方法调用,但method.getTarget().isAnnotatedWith(ExistForTesting.class))
总是返回false
.
我究竟做错了什么?