AssertJ简介

JUnit和Hamcrest

学Java的一定知道JUnit吧,它是一个著名的Java单元测试框架。我们在使用JUnit测试的时候,一般情况下会使用它的Assert类下的各种assertXXX方法。如果是细心一点的用户可能会发现JUnit包含了一个依赖Hamcrest,这是一个断言库。我们可以使用断言库来进行复杂的断言操作。

但是Hamcrest有几个缺点:一是缺乏更新,我看了看MavenCentral上,Hamcrest库最近更新还是2014年,因此对新的Java 8支持可能不够充分;二是Matcher分散在多个类中,编写困难,我们为了编写类似assertThat(responseString, anyOf(containsString("color"), containsString("colour")));这样的代码,需要静态引入多个类(使用IDEA还好,用Eclipse的静态导入更麻烦);三是JUnit仅依赖了Hamcrest核心包,只附带了最基本的断言功能,如果我们希望断言数字大小之类的话,还需要自己引入Hamcrest完整包,比较麻烦。

AssertJ

Hamcrest缺点不少,自然有更好的类库出现。FEST就是其中之一。不幸的是,FEST也很久不更新了。有人就在FEST的基础上,增加了很多新功能,这就是AssertJ

AssertJ有1、2、3三个版本,分别用于JDK6、7、8(及以上)。要在JDK 8中使用AssertJ,在项目中添加如下依赖(假如你使用的是Gradle)。

testCompile 'org.assertj:assertj-core:3.6.2'

然后在测试类中静态导入所有断言。

import static org.assertj.core.api.Assertions.*;

然后就很简单了。在测试方法中需要断言的地方键入assertThat即可。

assertThat(objectUnderTest).//断言操作

由于AssertJ的断言操作全在一个类中,所以当我们输入.之后,IDE就会嗖嗖的把所有断言列出来。

AssertJ支持所有Java基本类型,所以我们只要引入这一个包就可以满足大多数需求。如果需要JodaTime等支持,引入相应AssertJ扩展即可。由于AssertJ使用确实很简单,所以我感觉没什么写的了。有需要的话看看它的官网上的文档即可。

参考资料

https://github.com/junit-team/junit4/wiki/Matchers-and-assertthat

https://joel-costigliola.github.io/assertj/assertj-core.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AssertJ 是 JAVA 的流畅断言库。示例代码:// unique entry point to get access to all assertThat methods and utility methods (e.g. entry) import static org.assertj.core.api.Assertions.*;  // common assertions assertThat(frodo.getName()).isEqualTo("Frodo"); assertThat(frodo).isNotEqualTo(sauron)                  .isIn(fellowshipOfTheRing);  // String specific assertions assertThat(frodo.getName()).startsWith("Fro")                            .endsWith("do")                            .isEqualToIgnoringCase("frodo");  // collection specific assertions assertThat(fellowshipOfTheRing).hasSize(9)                                .contains(frodo, sam)                                .doesNotContain(sauron);  // using extracting magical feature to check fellowshipOfTheRing characters name :) assertThat(fellowshipOfTheRing).extracting("name").contains("Boromir", "Gandalf", "Frodo", "Legolas")                                                   .doesNotContain("Sauron", "Elrond");  // map specific assertions, ringBearers initialized with the elves rings and the one ring bearers. assertThat(ringBearers).hasSize(4)                        .contains(entry(oneRing, frodo), entry(nenya, galadriel))                        .doesNotContainEntry(oneRing, aragorn);  // and many more assertions : dates, file, numbers, exceptions ... 标签:AssertJ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值