什么是惯用的Hamcrest模式断言迭代的每个元素匹配给定的匹配器? [英] What is the idiomatic Hamcrest pattern to assert that each element of an iterable matches a given matcher?

查看:172
本文介绍了什么是惯用的Hamcrest模式断言迭代的每个元素匹配给定的匹配器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查以下片段:

    assertThat(
        Arrays.asList("1x", "2x", "3x", "4z"),
        not(hasItem(not(endsWith("x"))))
    );

这断言列表没有不以x结尾的元素。当然,这是表示列表中所有元素都以x结尾的双重否定方式。

This asserts that the list doesn't have an element that doesn't end with "x". This, of course, is the double negatives way of saying that all elements of the list ends with "x".

另请注意,该片段会抛出:

Also note that the snippet throws:

java.lang.AssertionError: 
Expected: not a collection containing not a string ending with "x"
     got: <[1x, 2x, 3x, 4z]>

这列出了整个列表,而不仅仅是不以x结尾的元素。

This lists the entire list, instead of just the element that doesn't end with "x".

所以有一种习惯的方式:

So is there an idiomatic way of:


  • 断言每个元素结束使用x(没有双重否定)

  • 在断言错误时,仅列出那些不以x结尾的元素

推荐答案

David Harkness给出的匹配器为预期的部分产生了一个很好的信息。
然而,实际部分的消息也取决于您使用的 assertThat 方法:

The matcher given by David Harkness produces a nice message for the expected part. The message for the actual part, however, is also determined by which assertThat method you use:

来自 JUnit org.junit.Assert.assertThat )的那个产生你提供的输出。

The one from JUnit (org.junit.Assert.assertThat) produces the output you provided.


  • 使用 not(hasItem(not(...))) matcher :

  • With the not(hasItem(not(...))) matcher:

java.lang.AssertionError: 
Expected: not a collection containing not a string ending with "x"
     got: <[1x, 2x, 3x, 4z]>


  • 使用 everyItem(...) matcher:

    java.lang.AssertionError: 
    Expected: every item is a string ending with "x"
         got: <[1x, 2x, 3x, 4z]>
    


  • Hamcrest中的那个 org.hamcrest.MatcherAssert.assertThat )产生David给出的输出:

    The one from Hamcrest (org.hamcrest.MatcherAssert.assertThat) produces the output given by David:


    • 使用 not(hasItem(not(...))) matcher:

    java.lang.AssertionError: 
    Expected: not a collection containing not a string ending with "x"
         but: was <[1x, 2x, 3x, 4z]>
    


  • 使用 everyItem(...) matcher:

    java.lang.AssertionError: 
    Expected: every item is a string ending with "x"
         but: an item was "4z"
    


  • 我自己对Hamcrest声明的实验表明,但是部分经常令人困惑,这取决于多个匹配器的组合方式以及哪一个首先失败,因此我仍然坚持使用JUnit断言,我知道完全是我在得到部分中看到的。

    My own experimentation with the Hamcrest assert showed me that the "but" part is often confusing, depending on how exactly multiple matchers are combined and which one fails first, and therefore I still stick to the JUnit assert, where I know quite exactly what I'll see in the "got" part.

    这篇关于什么是惯用的Hamcrest模式断言迭代的每个元素匹配给定的匹配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆