验证 Collection的相等性与莫基托?

发布于 2024-12-18 07:03:49 字数 428 浏览 2 评论 0原文

我正在使用 Mockito 进行单元测试,并且遇到了一个问题,我有一个哈希集合,并且我想验证参数是否相等。

即我有类似的东西

Collection< byte[] > blobs = new ArrayList< byte[] >();

// Do some stuff, omitted for brevity

verify( mockStore ).setWhatever( eq( blobs ) );

This 失败了,因为 byte[] 上的 'equals()' 进行了引用比较(并且它不是相同的引用)。

我是否缺少一些简单的东西来比较两个 byte[] 集合?我需要使用特殊的匹配器来进行比较吗?通常我会使用 Arrays.equal(),但我不知道如何告诉 Mockito 使用它来比较元素。建议?

I'm using Mockito for my unit testing, and I've run across an issue where I have a collection of hashes, and I want to verify that the parameters were equivalent.

i.e. I have something like

Collection< byte[] > blobs = new ArrayList< byte[] >();

// Do some stuff, omitted for brevity

verify( mockStore ).setWhatever( eq( blobs ) );

This fails, since 'equals()' on byte[]'s does a reference compare (and it's not the same reference).

Is there something simple I'm missing to compare two collections of byte[]'s? Is there a special matcher that I need to use for the comparison? Normally I'd use Arrays.equal(), but I don't know how to tell Mockito to use that for comparing the elements. Suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清泪尽 2024-12-25 07:03:49

没有 deepEquals mockito 匹配器。但是,您可以在某些测试助手中编写一个代码,例如:

public static Collection<byte[]> sameHashes(Collection<byte[]> hashes) {
    class CollectionOfHashesMatcher extends ArgumentMatcher<Collection<byte[]>> {
        public boolean matches(Collection<byte[] actualListOfHashes) { /* ... */ }        
        public void describeTo(Description description) { /* ... */ }        
    };
    return argThat(new CollectionOfHashesMatcher(hashes));
}

应该给出如下内容:

verify(mockStore).setWhatever(sameHashes(blobs));

There's no deepEquals mockito matcher. However you could code one in some test helper, for example :

public static Collection<byte[]> sameHashes(Collection<byte[]> hashes) {
    class CollectionOfHashesMatcher extends ArgumentMatcher<Collection<byte[]>> {
        public boolean matches(Collection<byte[] actualListOfHashes) { /* ... */ }        
        public void describeTo(Description description) { /* ... */ }        
    };
    return argThat(new CollectionOfHashesMatcher(hashes));
}

Which should give soemthing like :

verify(mockStore).setWhatever(sameHashes(blobs));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文