在单元测试中验证 Set 值的最佳方法是什么?

发布于 2024-09-05 22:32:15 字数 101 浏览 2 评论 0原文

好的,通常我会有一个返回某种 Set 的方法。单元测试这种方法的问题在于,不能保证集合上的迭代始终以相同的顺序返回项目。

有人有验证集合的首选方法吗?

彼得

Okay, often I'll have a method that returns a Set of some sort. The problem with unit testing such a method is that there is no guarantee an iteration over the set will always return the items in the same order.

Does anyone have any preferred method of validating a Set?

Peter

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

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

发布评论

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

评论(2

千里故人稀 2024-09-12 22:32:15

只需将预期值放入 Set 中,然后对预期值和实际值使用 assertEquals 即可。这很有魅力,例如

Set<String> expected = new HashSet<String>(Arrays.asList("expected", "items"));
...
Set<String> actual = ...;
Assert.assertEquals(expected, actual);

Just put your expected values in a Set and then use assertEquals on the expected and actual set. That works a charm, e.g.

Set<String> expected = new HashSet<String>(Arrays.asList("expected", "items"));
...
Set<String> actual = ...;
Assert.assertEquals(expected, actual);
囍孤女 2024-09-12 22:32:15

两组是相等的,这意味着它们包含相同的项目,如果它们都包含彼此的话

Assert.assertTrue(s1.containsAll(s2) && s2.containsAll(s1))

还有 SetUtils.isEqualSet

Two sets are equal, meaning they contain the same items, if they both contain one another

Assert.assertTrue(s1.containsAll(s2) && s2.containsAll(s1))

There's also SetUtils.isEqualSet

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