ArchUnit - 确保方法参数被注释

ArchUnit - ensure method parameters are annotated

我正在尝试编写一个 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)

在这种情况下规则应该如何正常工作?

P.S。在进行了一些调试之后,发现 haveRawParameterTypes 检查参数类型 (classes) 是否被注释,而不是方法参数本身。所以它查看 String class 并发现它没有用 @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));
    }
  };
}