本文介绍了jUnit 中的 CollectionAssert?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与 NUnit 的 CollectionAssert?

Is there a jUnit parallel to NUnit's CollectionAssert?

推荐答案

使用 JUnit 4.4,您可以将 assertThat()Hamcrest 代码(别担心,它随 JUnit 一起提供,不需要额外的 .jar)来生成复杂的自描述断言,包括那些对集合进行操作:

Using JUnit 4.4 you can use assertThat() together with the Hamcrest code (don't worry, it's shipped with JUnit, no need for an extra .jar) to produce complex self-describing asserts including ones that operate on collections:

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;

List<String> l = Arrays.asList("foo", "bar");
assertThat(l, hasItems("foo", "bar"));
assertThat(l, not(hasItem((String) null)));
assertThat(l, not(hasItems("bar", "quux")));
// check if two objects are equal with assertThat()

// the following three lines of code check the same thing.
// the first one is the "traditional" approach,
// the second one is the succinct version and the third one the verbose one
assertEquals(l, Arrays.asList("foo", "bar")));
assertThat(l, is(Arrays.asList("foo", "bar")));
assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));

使用这种方法,您将在断言失败时自动获得对断言的良好描述.

Using this approach you will automagically get a good description of the assert when it fails.

这篇关于jUnit 中的 CollectionAssert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 11:57