gpt4 book ai didi

java - ArchUnit - 确保方法参数被注释

转载 作者:行者123 更新时间:2023-12-04 17:23:44 25 4
gpt4 key购买 nike

我正在尝试编写一个 ArchUnit 测试规则,它应该确保用 @ComponentInterface 注释的接口(interface)注释具有用 @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)在这种情况下,规则应该如何正常工作?
附言在做了一些调试之后,结果是 hasRawParameterTypes 检查参数类型(类)是否被注释,而不是方法参数本身。所以它查看 String 类并发现它没有用 @Input 注释。很高兴知道,但这并不能解决问题。

最佳答案

您始终可以使用反射 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));
}
};
}

关于java - ArchUnit - 确保方法参数被注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64699060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com