sách gpt4 ai đã đi

java - 滥用 hamcrest hasItems

In lại 作者:塔克拉玛干 更新时间:2023-11-03 03:17:38 25 4
mua khóa gpt4 Nike

我有一个整数列表(当前),我想检查这个列表是否包含预期列表中的所有元素,甚至不包含列表 notExpected 中的一个元素,所以代码如下:

    List expected= new ArrayList();
expected.add(1);
expected.add(2);

List notExpected = new ArrayList();
notExpected.add(3);
notExpected.add(4);

List current = new ArrayList();
current.add(1);
current.add(2);


assertThat(current, not(hasItems(notExpected.toArray(new Integer[expected.size()]))));

assertThat(current, (hasItems(expected.toArray(new Integer[expected.size()]))));

这么久了。但是当我添加

    current.add(3);

测试也是绿色的。我是否滥用了 hamcrest 匹配器?顺便说一句。

    for (Integer i : notExpected)
assertThat(current, not(hasItem(i)));

给了我正确的答案,但我认为我可以很容易地使用 hamcrest 匹配器来解决这个问题。我正在使用 junit 4.11 和 hamcrest 1.3

1 Câu trả lời

hasItems(notExpected...) 只会匹配 hiện hành 如果来自 notExpected 的所有元素也在 hiện hành >。所以用线

assertThat(current, not(hasItems(notExpected...)));

您断言 hiện hành 不包含 notExpected TRONG所有元素.

断言 hiện hành 不包含来自 notExpected của任何元素 的一种解决方案:

assertThat(current, everyItem(not(isIn(notExpected))));

然后您甚至不必将列表转换为数组。这种变体可能更具可读性,但需要转换为数组:

assertThat(current, everyItem(not(isOneOf(notExpected...))));

请注意,这些匹配器并非来自 hamcrest-core TRONG CoreMatchers,因此您需要添加对 hamcrest-library 的依赖。


org.hamcrest
hamcrest-library
1.3

关于java - 滥用 hamcrest hasItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14932363/

25 4 0
Bài viết được đề xuất: java - HTTP 状态 415 - 不支持的媒体类型
Bài viết được đề xuất: arrays - 确定一个非常大的数组是否包含重复项
Bài viết được đề xuất: algorithm - 最接近的相等数
Bài viết được đề xuất: java - 如何检查 JZMQ 套接字是否已连接
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com