【问题标题】:ArchUnit ensuring annotation presenceArchUnit 确保注释存在
【发布时间】:2019-11-04 18:05:02
【问题描述】:

鉴于版本 0.12 中的 ArchUnit 库:

是否可以测试一个场景“用A 注释的方法也应该用B 注释或在用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 根本没有帮助。我可以将最后一行替换为满足断言“在带有B 注释的类型中声明的方法”的任何工作吗?

【问题讨论】:

    标签: java unit-testing archunit


    【解决方案1】:

    原来我不必要地尝试将参数传递给orShould 方法。为了实现我的目标,应该使用无参数方法扩展规则:

    methods()
        .that()
        .areAnnotatedWith(A.class)
        .should()
        .beAnnotatedWith(B.class)
        .orShould()
        .beDeclaredInClassesThat()
        .areAnnotatedWith(B.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多