我以前曾在博客中介绍过Hamcrest ,并使用其assertThat方法优先于JUnit的Assert 。
但是,我很快发现了FEST断言 ,并愉快地切换到它。 它提供了与Hamcrest相同的改进的测试可读性,并改善了故障消息,但具有启用IDE自动完成功能的额外好处,而不必搜索软件包和类文档以找到合适的匹配器。
不幸的是,Fest似乎不再被积极开发。 1.x分支的最后一个稳定版本1.4于2011年发布,而新的2.x分支从未使其成为稳定版本,并且自2013年6月以来就没有提交过。
输入AssertJ …
断言J
AssertJ是Fest Assert的一个分支 ,并且似乎提供了所有好处以及一系列新功能 。
馆藏
例如,它具有我最喜欢Fest的所有漂亮集合处理:
List<String> stringList = Lists.newArrayList("A", "B", "C");
assertThat(stringList).contains("A"); //true
assertThat(stringList).doesNotContain("D"); //true
assertThat(stringList).containsOnly("A"); //false
assertThat(stringList).containsExactly("A", "C", "B"); //false
assertThat(stringList).containsExactly("A", "B", "C"); //true
失败前收集所有错误
它还具有在发生故障之前捕获所有故障的能力。 例如,上述示例将作为第一个失败的假设而失败。 下面的示例使您可以查看所有失败的断言:
List<String> stringList = Lists.newArrayList("A", "B", "C");
SoftAssertions softly = new SoftAssertions();
softly.assertThat(stringList).contains("A"); //true
softly.assertThat(stringList).containsOnly("A"); //false
softly.assertThat(stringList).containsExactly("A", "C", "B"); //false
softly.assertThat(stringList).containsExactly("A", "B", "C"); //true
// Don't forget to call SoftAssertions global verification!
softly.assertAll();
并产生如下消息:
The following 2 assertions failed:
1)
Expecting:
<["A", "B", "C"]>
to contain only:
<["A"]>
elements not found:
<[]>
and elements not expected:
<["B", "C"]>
2)
Actual and expected have the same elements but not in the same order, at index 1 actual element was:
<"B">
whereas expected element was:
<"C">
绝对值得一看。 AssertJ核心代码和问题跟踪器托管在github上。
翻译自: https://www.javacodegeeks.com/2014/10/assertj-fest-hamcrest.html