【发布时间】:2016-04-06 06:06:40
【问题描述】:
以下代码旨在允许对流的大小进行更自然的断言。
Matcher<Stream> hasCount(int count) {
return new TypeSafeDiagnosingMatcher<Stream>() {
protected boolean matchesSafely(Stream stream, Description desc) {
long streamCount = stream.count();
if (streamCount == count) {
return true;
} else {
desc.appendText("count ").appendValue(streamCount);
return false;
}
}
public void describeTo(Description desc) {
desc.appendText("count ").appendValue(count);
}
};
}
这允许断言,例如:
assertThat(getWidgetStream(), hasCount(52));
断言通过时它工作正常,但当它失败时(例如assertThat(Stream.empty(), hasCount(1));)它返回错误
“流已被操作或关闭”而不是预期的描述“预期:计数 有:计数 ”。
当我检查 TypeSafeDiagnosingMatcher 的源时,我发现 matchesSafely 是从 matches 和 describeMismatch 调用的。所以 Hamcrest 假设 matchesSafely 是幂等的,而我的不是。
有没有办法解决这个问题?
【问题讨论】:
-
Hamcrest documentation 建议“使用 Hamcrest 时,无法保证调用
matches()或describeMismatch()的频率,因此作为实际参数传递的对象在引用时不应更改. 如果您正在测试流,一个好的做法是在匹配之前收集流的内容。"