Java JUnit 4 比较集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2313229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:01:25  来源:igfitidea点击:

JUnit 4 compare Sets

javaunit-testingcollectionsjunit

提问by Eqbal

How would you succinctly assert the equality of Collectionelements, specifically a Setin JUnit 4?

您将如何简洁地断言Collection元素的相等性,特别是SetJUnit 4 中的 a ?

采纳答案by Bill the Lizard

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

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

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 @Testwill pass if the two Sets are the same size and contain the same elements.

@Test如果两个Sets 的大小相同并且包含相同的元素,这将通过。

回答by dfa

with hamcrest:

火腿

assertThat(s1, is(s2));

with plain assert:

使用简单的断言:

assertEquals(s1, s2);

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

所述T的equals()方法:NB混凝土组类是用来

回答by Roman

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);  
}  

回答by Bill the Lizard

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.

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

回答by Matt Friedman

Apache commons to the rescue again.

Apache 公地再次来救援。

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.

奇迹般有效。我不知道为什么,但我发现对于集合,以下内容assertEquals(coll1, coll2)并不总是有效。在我失败的情况下,我有两个由 Sets 支持的集合。hamcrest 和 junit 都不会说这些集合是相等的,即使我确定它们是相等的。使用 CollectionUtils 它可以完美运行。

回答by jayunit100

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 :

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

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.

方法对您来说更具可读性和可调试性(所有集合都支持 toArray(),因此使用 ArrayAssert 方法应该很容易。

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

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

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

回答by Hans-Peter St?rr

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:

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

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.)

(诚​​然,这不是一个特别干净的方法,无法区分一个元素“foo,bar”和两个元素“foo”和“bar”。但在实践中我认为最重要的是编写测试简单快捷,否则许多开发人员不会不按要求执行。)

回答by Hans-Peter St?rr

Using Hamcrest:

使用 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.

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

回答by FLUXparticle

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

我喜欢 Hans-Peter St?rr 的解决方案......但我认为它不太正确。遗憾的containsInAnyOrder是不接受一个Collectionobjetcs 来比较。因此,它必须是一个CollectionMatcherS:

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;