AssertJ为Java提供了流式断言(Fluent assertions)。
// 为所有assertThat和工具方法提供唯一访问入口(例如entry)
import static org.assertj.core.api.Assertions.*;
// 下面的示例中,fellowshipOfTheRing是一个TolkienCharacter列表
// 简单断言
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron)
.isIn(fellowshipOfTheRing);
// String断言
assertThat(frodo.getName()).startsWith("Fro")
.endsWith("do")
.isEqualToIgnoringCase("frodo");
// 集合断言
assertThat(fellowshipOfTheRing).hasSize(9)
.contains(frodo, sam)
.doesNotContain(sauron);
// 使用extracting特性检查fellowshipOfTheRing中的名字:)
assertThat(fellowshipOfTheRing).extracting("name").contains("Boromir", "Gandalf", "Frodo", "Legolas")
.doesNotContain("Sauron", "Elrond");
// Java 8方式的extracting
assertThat(fellowshipOfTheRing).extracting(character -> character.getRace().getName())
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
// 断言之前过滤集合
assertThat(fellowshipOfTheRing).filteredOn("race", HOBBIT)
.containsOnly(sam, frodo, pippin, merry);
// 使用Java 8 lambda predicate过滤集合
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
.containsOnly(aragorn, frodo, legolas, boromir);
// 将extraction和过滤结合(是的,我们可以做到)
assertThat(fellowshipOfTheRing).filteredOn(character -> character.getName().contains("o"))
.containsOnly(aragorn, frodo, legolas, boromir)
.extracting(character -> character.getRace().getName())
.contains("Hobbit", "Elf", "Man");
// 支持多种其它断言:map、日期(Java 7和Java 8)、文件、数字、异常断言等
支持的开发库
Guava
为Guava类型提供断言,支持Multimap、Table、Optional或ByteSource。
可以关注AssertJ Guava断言的最新消息和文档。
Joda Time
为Joda Time提供断言,支持DateTime和LocalDateTime。更多断言支持即将发布,欢迎参加开发贡献!
可以关注AssertJ Joda Time断言的最新消息和文档。
Neo4J
为Neo4J提供断言。
可以关注AssertJ Neo4J断言的最新消息和文档。
Neo4J断言由Florent Biville开发。
主要特性
功能丰富且易于使用
AssertJ提供了丰富的断言集合,错误信息非常准确,提高了测试代码的可读性并且可以非常方便地在你喜爱的IDE中集成。
可以从一分钟上手指南开始,了解AssertJ的各种特性,并请关注最新版本的发布。
如果你被AssertJ打动,可以将JUnit断言自动转换为AssertJ。
可扩展
你可以非常容易地为自己的类编写断言,让测试断言更好地反映程序业务,这样就可以使用通用语言编写测试了!
我们提供了断言生成器,可以为你的业务模型类快速创建断言。
社区驱动
AssertJ是为了帮助开发社区,我们会倾听用户的想法并提供有用的断言。
AssertJ是Fest Assert开发库的分支(fork),该开发库目前已不再维护。
AssertJ承诺永远开源、免费。
开发资源
官方网站:joel-costigliola.github.io/assertj/
开源地址:github.com/joel-costig…