gpt4 book ai didi

java - 断言可迭代的每个元素都匹配给定匹配器的惯用 Hamcrest 模式是什么?

转载 作者:IT老高 更新时间:2023-10-28 20:21:43 24 4
gpt4 key购买 nike

检查以下代码段:

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

这断言列表中没有不以“x”结尾的元素。当然,这是双重否定的说法,即列表的所有元素都以“x”结尾。

另请注意,代码段会抛出:

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

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

那么有没有一种惯用的方式:

  • 断言每个元素都以“x”结尾(没有双重否定)
  • 在断言错误时,仅列出那些不以“x”结尾的元素

最佳答案

你正在寻找everyItem():

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

这会产生一个很好的失败消息:

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

关于java - 断言可迭代的每个元素都匹配给定匹配器的惯用 Hamcrest 模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5985610/

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