gpt4 book ai didi

java - 在具有特定属性的列表中仅存在一个项目的 Hamcrest 测试

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:35 25 4
gpt4 key购买 nike

通过 Hamcrest,我们可以轻松地测试列表中是否存在至少一个具有特定属性的项目,例如

List<Pojo> myList = ....

MatcherAssert.assertThat(myList, Matchers.hasItem(Matchers.<Pojo>hasProperty("fieldName", Matchers.equalTo("A funny string")))));

Pojo 是这样的:

public class Pojo{
private String fieldName;
}

这很好,但是我如何检查列表中是否恰好有一个对象具有特定的属性?

最佳答案

您可能必须为此编写自己的匹配器。 (我更喜欢 fest assertions 和 Mockito,但过去常常使用 Hamcrest...)

例如……

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.core.IsCollectionContaining;

public final class CustomMatchers {

public static <T> Matcher<Iterable<? super T>> exactlyNItems(final int n, Matcher<? super T> elementMatcher) {
return new IsCollectionContaining<T>(elementMatcher) {
@Override
protected boolean matchesSafely(Iterable<? super T> collection, Description mismatchDescription) {
int count = 0;
boolean isPastFirst = false;

for (Object item : collection) {

if (elementMatcher.matches(item)) {
count++;
}
if (isPastFirst) {
mismatchDescription.appendText(", ");
}
elementMatcher.describeMismatch(item, mismatchDescription);
isPastFirst = true;
}

if (count != n) {
mismatchDescription.appendText(". Expected exactly " + n + " but got " + count);
}
return count == n;
}
};
}
}

你现在可以做...

    List<TestClass> list = Arrays.asList(new TestClass("Hello"), new TestClass("World"), new TestClass("Hello"));

assertThat(list, CustomMatchers.exactlyNItems(2, hasProperty("s", equalTo("Hello"))));

当列表为...时示例失败输出

    List<TestClass> list = Arrays.asList(new TestClass("Hello"), new TestClass("World"));

...将...

Exception in thread "main" java.lang.AssertionError: 
Expected: a collection containing hasProperty("s", "Hello")
but: , property 's' was "World". Expected exactly 2 but got 1

(你可能想稍微定制一下)

顺便说一下,“TestClass”是...

public static class TestClass {
String s;

public TestClass(String s) {
this.s = s;
}

public String getS() {
return s;
}
}

关于java - 在具有特定属性的列表中仅存在一个项目的 Hamcrest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609476/

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