【问题标题】:Creating a Matcher<Stream> for jUnit为 jUnit 创建 Matcher<Stream>
【发布时间】: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 是从 matchesdescribeMismatch 调用的。所以 Hamcrest 假设 matchesSafely 是幂等的,而我的不是。

有没有办法解决这个问题?

【问题讨论】:

  • Hamcrest documentation 建议“使用 Hamcrest 时,无法保证调用 matches()describeMismatch() 的频率,因此作为实际参数传递的对象在引用时不应更改. 如果您正在测试流,一个好的做法是在匹配之前收集流的内容。"

标签: java junit hamcrest


【解决方案1】:

我发现的一个解决方案是在调用之间存储结果。

return new TypeSafeDiagnosingMatcher<Stream>() {
    private Optional<Long> streamCount = Optional.empty();

    protected boolean matchesSafely(Stream stream, Description desc) {
        if (!streamCount.isPresent())
            streamCount = Optional.of(stream.count());
        if (streamCount.get() == count) {
            return true;
        } else {
            desc.appendText("has count ").appendValue(streamCount.get().intValue());
            return false;
        }
    }
};

这可行,但不是特别优雅。

【讨论】:

  • 因为mtachedSafelydescribedTo 之后第二次被调用以生成but: ... 部分的说明。这似乎是要走的路。
  • @SubOptimal 是的,我怀疑这是最简单的解决方案,但假设 matchesSafely 可以被调用两次似乎有点差距。
  • 但是看着IsCollectionContainingTest.java,这似乎是预期的方式。
  • @SubOptimal 感谢您的链接 - 我认为您是正确的
  • 我在JavaHamcrest #144 上创建了一个问题报告,因为应该记录此行为或将其更改为对matchesSafely 的一次调用。
猜你喜欢
  • 2013-07-30
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多