jUnit 中的 CollectionAssert?

2024-05-02

是否有与 NUnit 并行的 jUnit?


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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jUnit 中的 CollectionAssert? 的相关文章

随机推荐