【问题标题】:Analog of everyItem() from Hamcrest in AssertJ来自 AssertJ 中 Hamcrest 的 everyItem() 的模拟
【发布时间】:2015-09-28 18:40:28
【问题描述】:

在 AssertJ 中是否有来自 Hamcrest 的 everyItem() 的类比?

我有一个电子邮件列表,需要进行断言以检查每封电子邮件是否包含子字符串“alex”。目前我可以用 AssertJ 做到这一点的唯一方法如下:

    List<String> actual = Arrays.asList("alex@gmail.com", "alex1@gmail.com", "ale2@hotmail.com", "bred@gmail.com");

    SoftAssertions softly = new SoftAssertions();
    for(String email: actual ) {
        softly.assertThat(email).contains("alex");
    }

    softly.assertAll();

也可以在没有软断言的情况下完成,但我更愿意检查列表中的所有项目。

还有更简洁的方法吗?具体来说,AssertJ 中有没有办法检查列表中的每个项目以匹配子字符串?

在 Hamcrest 中,我可以一行完成:

assertThat(actual, everyItem(containsString("alex")));

但在 AssertJ 中,无论如何我都必须手动遍历列表。

【问题讨论】:

    标签: java hamcrest assertj


    【解决方案1】:

    Assertj 3.6.0 引入了allSatisfy assertion,它允许您对可迭代的每个元素执行范围断言。

    因此你可以做你想做的事

    assertThat(actual).allSatisfy(elem -> assertThat(elem).contains("alex"));
    

    【讨论】:

      【解决方案2】:

      我找到了 2 个解决方案: 1) 使用 java 8

      actual.forEach( val -> softly.assertThat(val).contains("alex"));
      

      2) 创建一个实用类

      public class AssertUtils {
          public static Condition<String> ContainsCondition(String val) {
              return new Condition<String>() {
                  @Override
                  public boolean matches(String value) {
                      return value.contains(val);
                  }
              };
          }
      }
      

      并使用它:

      softly.assertThat(actual).are(AssertUtils.ContainsCondition("alex"));
      

      【讨论】:

        【解决方案3】:

        您可以使用谓词构建 AssertJ 条件并使用 are/have 断言:

         @Test
         public void condition_built_with_predicate_example() {
             Condition<String> fairyTale = new Condition<String>(s -> s.startsWith("Once upon a time"), "a %s tale", "fairy");
             String littleRedCap = "Once upon a time there was a dear little girl ...";
             String cindirella = "Once upon a time there was a ...";
             assertThat(asList(littleRedCap, cindirella)).are(fairyTale);
        

        }

        编辑:正如 Dan 所指出的,我现在将使用 allSatisfy

        【讨论】:

          【解决方案4】:

          我更喜欢使用这种形式的 allMatch,如下所示:

          assertThat(movies).extracting("title").allMatch(s -> s.toString().contains("the"));
          
          

          【讨论】:

            【解决方案5】:

            我只是依赖 Java 8 的流功能来处理这类事情:

            assertThat(actual.stream().allMatch(s -> s.contains("alex"))).isTrue();
            

            【讨论】:

            • 谢谢,我明白你的意思,但它会在失败时产生晦涩的信息,例如“期望 [true] 但结果为 [false]”
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-08-13
            • 1970-01-01
            • 1970-01-01
            • 2012-04-20
            • 1970-01-01
            相关资源
            最近更新 更多