我正在尝试编写一个ArchUnit测试规则,它应该确保用@ComponentInterface注释注释的接口具有带有@Input注释的方法参数。如下所示:
ArchRule rule =
methods()
.that()
.areDeclaredInClassesThat()
.areInterfaces()
.and()
.areDeclaredInClassesThat()
.areAnnotatedWith(ComponentInterface.class)
.should()
.haveRawParameterTypes(
allElements(CanBeAnnotated.Predicates.annotatedWith(Input.class)));接口如下所示:
@ComponentInterface
public interface AdminComponent {
void login(@Input(name = "loginString") String loginString);
}但是测试失败了,出现了如下错误:Method < com.some.package.AdminComponent.login(java.lang.String)> does not have raw parameter types all elements annotated with @Input in (AdminComponent.java:0)
在这种情况下,规则应该如何正确地工作呢?
在进行了一些调试之后,结果发现haveRawParameterTypes检查参数类型(类)是否有注释,而不是方法参数本身。因此,它查看String类并发现,它没有使用@Input进行注释。很高兴知道,但这不能解决问题。
发布于 2021-07-12 22:48:02
您可以始终回到反射API:
ArchRule rule = methods()
.that().areDeclaredInClassesThat().areInterfaces()
.and().areDeclaredInClassesThat().areAnnotatedWith(ComponentInterface.class)
.should(haveAllParametersAnnotatedWith(Input.class));
ArchCondition<JavaMethod> haveAllParametersAnnotatedWith(Class<? extends Annotation> annotationClass) {
return new ArchCondition<JavaMethod>("have all parameters annotated with @" + annotationClass.getSimpleName()) {
@Override
public void check(JavaMethod method, ConditionEvents events) {
boolean areAllParametersAnnotated = true;
for (Annotation[] parameterAnnotations : method.reflect().getParameterAnnotations()) {
boolean isParameterAnnotated = false;
for (Annotation annotation : parameterAnnotations) {
if (annotation.annotationType().equals(annotationClass)) {
isParameterAnnotated = true;
}
}
areAllParametersAnnotated &= isParameterAnnotated;
}
String message = (areAllParametersAnnotated ? "" : "not ")
+ "all parameters of " + method.getDescription()
+ " are annotated with @" + annotationClass.getSimpleName();
events.add(new SimpleConditionEvent(method, areAllParametersAnnotated, message));
}
};
}发布于 2022-07-12 18:40:23
请注意,该信息同时可用(但尚未添加到fluent API中) -> https://github.com/TNG/ArchUnit/pull/701
您可以通过定制的ArchCondition来实现它
methods()
...
.should(haveParametersAnnotatedWith(Input.class))
// ...
private ArchCondition<JavaMethod> haveParametersAnnotatedWith(
Class<? extends Annotation> annotationType
) {
return new ArchCondition<JavaMethod>(
"have parameters annotated with @" + annotationType.getSimpleName()
) {
@Override
public void check(JavaMethod method, ConditionEvents events) {
method.getParameters().stream()
.filter(parameter -> !parameter.isAnnotatedWith(annotationType))
.forEach(parameter -> events.add(SimpleConditionEvent.violated(method,
parameter.getDescription() + " is not annotated with @" + annotationType.getSimpleName())));
}
};
}https://stackoverflow.com/questions/64699060
复制相似问题