gpt4 book ai didi

java - 如何将复杂对象列表的成员与 Hamcrest 进行比较?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:53:34 26 4
gpt4 key购买 nike

假设我有一个 List<A>哪里

class A {
private Integer val;
private String name;
}

在我的测试用例中,我得到了这个列表,其大小和内容都不确定。我想做的是比较 val我知道必须在给定 name 的列表中的两个列表元素的字段字段;

List<A> list = logic.getList();
assertThat(list, allOf(hasItems(hasProperty("name", equalTo("first")),
hasItems(hasProperty("val", equalTo(***value from another member with name = "second"))));

我怎样才能做到这一点,或者这甚至可以通过 Hamcrest Matchers 实现?

最佳答案

您可以根据需要实现自定义 Matcher,例如检查某些具有名称的项目是否具有相同的值字段:

final class FooTest {

static final class Foo {

final int val;
final String name;

// all args constructor
}

// custom matcher
static final class FoosHasSameValues extends TypeSafeMatcher<List<Foo>> {

private final Set<String> names;

// all args constructor

FoosHasSameValues(final String... names) {
this(new HashSet<>(Arrays.asList(names)));
}

@Override
protected boolean matchesSafely(final List<Foo> items) {
final List<Integer> values = items.stream()
// filter only items with specified names
.filter(i -> this.names.contains(i.name))
// select only values
.map(i -> i.val)
.collect(Collectors.toList());
if (values.size() != this.names.size()) {
// matching failed if list doesn't contains all
// needed items with names
return false;
}
// check https://stackoverflow.com/a/29288616/1723695
return values.stream().distinct().limit(2).count() <= 1;
}

@Override
public void describeTo(final Description description) {
description.appendText("has items [")
.appendValue(String.join(", ", this.names))
.appendText("] with same values");
}
}

@Test
void testMatchers() throws Exception {
MatcherAssert.assertThat(
Arrays.asList(
new Foo("first", 1),
new Foo("second", 1),
new Foo("third", 2)
),
new FoosHasSameValues("first", "second")
);
}
}

关于java - 如何将复杂对象列表的成员与 Hamcrest 进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625209/

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