如何断言 Set 具有具有 hamcrest 确切属性的项目

Szy*_*pek 6 java assert mocking hamcrest mockito

我一直在尝试使用此解决方案断言我的 Set 具有具有 hamcrest 给定属性的集合,但我有:

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V at org.hamcrest.Condition$Matched.matching(Condition.java:52)

进口:

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;
Run Code Online (Sandbox Code Playgroud)

代码:

assertThat(mySet, contains(hasProperty("id", equalTo("expectedId"))));
Run Code Online (Sandbox Code Playgroud)

您有什么想法如何很好地维护它吗?

Gho*_*ica 3

好吧,您应该尝试让assertThat 为您完成工作。

Set<WhateverPropertyTypeYouAreUsing> expectedSet = Collections.singleton( ... create a property object with that id/value);

assertThat(mySet, is(expectedSet))
Run Code Online (Sandbox Code Playgroud)

这里的限制:假设您的集合仅包含该一个属性值。

否则,您可以选择:

assertThat(mySet.contains(someProperty), is(true))
Run Code Online (Sandbox Code Playgroud)

(可能带有附加消息以更好地描述失败的断言)。

先决条件:您的属性类应该以合理的方式实现 equals() 。