JUnit 4 比较集

发布于 2024-08-22 16:37:09 字数 80 浏览 3 评论 0原文

您如何简洁地断言 Collection 元素(特别是 JUnit 4 中的 Set)的相等性?

How would you succinctly assert the equality of Collection elements, specifically a Set in JUnit 4?

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

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

发布评论

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

评论(11

月野兔 2024-08-29 16:37:10

您可以断言两个 Set 彼此相等,这会调用 Set equals() 方法

public class SimpleTest {

    private Set<String> setA;
    private Set<String> setB;

    @Before
    public void setUp() {
        setA = new HashSet<String>();
        setA.add("Testing...");
        setB = new HashSet<String>();
        setB.add("Testing...");
    }

    @Test
    public void testEqualSets() {
        assertEquals( setA, setB );
    }
}

如果两个 Set 大小相同且包含相同元素,则此 @Test 将通过。

You can assert that the two Sets are equal to one another, which invokes the Set equals() method.

public class SimpleTest {

    private Set<String> setA;
    private Set<String> setB;

    @Before
    public void setUp() {
        setA = new HashSet<String>();
        setA.add("Testing...");
        setB = new HashSet<String>();
        setB.add("Testing...");
    }

    @Test
    public void testEqualSets() {
        assertEquals( setA, setB );
    }
}

This @Test will pass if the two Sets are the same size and contain the same elements.

反话 2024-08-29 16:37:10

Apache Commons 再次拯救了我们。

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

就像魅力一样。我不知道为什么,但我发现对于集合,以下 assertEquals(coll1, coll2) 并不总是有效。如果我失败了,我有两个由 Sets 支持的集合。 hamcrest 和 junit 都不会说这些集合是平等的,尽管我确信它们是平等的。使用 CollectionUtils 它可以完美地工作。

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

〆凄凉。 2024-08-29 16:37:10

with hamcrest

assertThat(s1, is(s2));

使用普通断言:

assertEquals(s1, s2);

注意:t 的 equals() 方法使用具体集合类

with hamcrest:

assertThat(s1, is(s2));

with plain assert:

assertEquals(s1, s2);

NB:t the equals() method of the concrete set class is used

记忆で 2024-08-29 16:37:10

一个特别有趣的情况是,当您比较

   java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]> 

   java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>

时,到目前为止,我看到的唯一解决方案是将它们都更改为集合

assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));

,或者我可以逐个元素地比较它们。

A particularly interesting case is when you compare

   java.util.Arrays$ArrayList<[[name,value,type], [name1,value1,type1]]> 

and

   java.util.Collections$UnmodifiableCollection<[[name,value,type], [name1,value1,type1]]>

So far, the only solution I see is to change both of them into sets

assertEquals(new HashSet<CustomAttribute>(customAttributes), new HashSet<CustomAttribute>(result.getCustomAttributes()));

Or I could compare them element by element.

嘿哥们儿 2024-08-29 16:37:10

作为基于数组的附加方法......您可以考虑在 junitx 中使用无序数组断言。虽然 Apache CollectionUtils 示例可以工作,但那里也有一个可靠的断言扩展包:

我认为该

ArrayAssert.assertEquivalenceArrays(new Integer[]{1,2,3}, new Integer[]{1,3,2});

方法对您来说将更具可读性和可调试性(所有集合都支持 toArray(),因此它应该足够容易使用 当然,

这里的缺点是,junitx 是一个额外的 jar 文件或 Maven 条目...

 <dependency org="junit-addons" name="junit-addons" rev="1.4"/>

As an additional method that is array based ... you can consider using unordered array assertions in junitx . Although the Apache CollectionUtils example will work, there is a pacakge of solid assertion extensions there as well :

I think that the

ArrayAssert.assertEquivalenceArrays(new Integer[]{1,2,3}, new Integer[]{1,3,2});

approach will be much more readable and debuggable for you (all Collections support toArray(), so it should be easy enough to use the ArrayAssert methods.

Of course the downside here is that, junitx is an additional jar file or maven entry...

 <dependency org="junit-addons" name="junit-addons" rev="1.4"/>
澜川若宁 2024-08-29 16:37:10

我喜欢 Hans-Peter Störr 的解决方案......但我认为它不太正确。遗憾的是 containsInAnyOrder 不接受要比较的对象 Collection。所以它必须是 MatcherCollection

assertThat(set1, containsInAnyOrder(set2.stream().map(IsEqual::equalTo).collect(toList())))

导入是:

import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;

I like the solution of Hans-Peter Störr... But I think it is not quite correct. Sadly containsInAnyOrder does not accept a Collection of objetcs to compare to. So it has to be a Collection of Matchers:

assertThat(set1, containsInAnyOrder(set2.stream().map(IsEqual::equalTo).collect(toList())))

The import are:

import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertThat;
著墨染雨君画夕 2024-08-29 16:37:10

检查 这篇文章。其中的一个例子:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  

Check this article. One example from there:

@Test  
public void listEquality() {  
    List<Integer> expected = new ArrayList<Integer>();  
    expected.add(5);  

    List<Integer> actual = new ArrayList<Integer>();  
    actual.add(5);  

    assertEquals(expected, actual);  
}  
梦毁影碎の 2024-08-29 16:37:10

使用 Hamcrest:

assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));

当集合具有不同的数据类型时,这也适用,并报告差异而不是仅仅失败。

Using Hamcrest:

assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));

This works also when the sets have different datatypes, and reports on the difference instead of just failing.

誰認得朕 2024-08-29 16:37:10

你可以这样做 ->
assertThat(actualSet).containsExactlyInAnyOrder(expectedSet);

You can do it like that ->
assertThat(actualSet).containsExactlyInAnyOrder(expectedSet);

℉絮湮 2024-08-29 16:37:10

如果您想检查 List 或 Set 是否包含一组特定值(而不是将其与已存在的集合进行比较),通常集合的 toString 方法很方便:

String[] actualResult = calltestedmethod();
assertEquals("[foo, bar]", Arrays.asList(actualResult).toString());

List otherResult = callothertestedmethod();
assertEquals("[42, mice]", otherResult.toString());

这比首先构造预期集合并比较要短一些它与实际集合相结合,并且更容易编写和纠正。

(诚​​然,这不是一个特别干净的方法,并且无法区分元素“foo,bar”和两个元素“foo”和“bar”。但在实践中我认为最重要的是编写测试既简单又快速,否则许多开发人员在没有压力的情况下就不会这样做。)

If you want to check whether a List or Set contains a set of specific values (instead of comparing it with an already existing collection), often the toString method of collections is handy:

String[] actualResult = calltestedmethod();
assertEquals("[foo, bar]", Arrays.asList(actualResult).toString());

List otherResult = callothertestedmethod();
assertEquals("[42, mice]", otherResult.toString());

This is a bit shorter than first constructing the expected collection and comparing it with the actual collection, and easier to write and correct.

(Admittedly, this is not a particularily clean method, and can't distinguish an element "foo, bar" from two elements "foo" and "bar". But in practice I think it's most important that it's easy and fast to write tests, otherwise many developers just won't without being pressed.)

花落人断肠 2024-08-29 16:37:10

containsInAnyOrder() - 帮助我。

containsInAnyOrder() - help me.

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