?引言
做过接口测试的同学一般都用过TestNG或者JUnit。TestNG或者JUnit是第一代断言工具。Hamcrest 属于第二代的断言工具,Hamcrest这个单词是”matchers”的变位词。它提供了大量丰富的匹配器,能够让断言可读性更高,断言样板代码量更小,更易维护。Hamcrest一经问世,就取得了非常大的成功,甚至一度成为第一个被Junit引入的第三方包,成为Junit4断言的一部分。熟悉Rest-assured的同学应该知道它内置断言风格就是Hamcrest。
AssertJ与之前的断言工具的最大不同,是引入了流式断言(Fluent Assertion),让断言的编写更加流畅,可读性更强,从而让它大获成功。
导入
只需要在Pom.xml引入以下依赖:
<dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.11.1</version></dependency>
小试牛刀
import org.testng.annotations.Test;import static org.assertj.core.api.Assertions.*;?public class DemoTests { @Test public void simpleAssertJTest(){ assertThat("The Lord of the Rings").isNotNull() .startsWith("The") .contains("Lord") .endsWith("Rings"); }}
流式断言是不是看起来很舒服。静态导入AssertJ就不用像这样Assertions.assertThat()每个语言前都要加一个Assertions了。
断言描述
当用例执行失败后,我们通常会打印描述。我们可以这样设置as(String description, Object… args)。一定要记得as要放在断言前。
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);??// failing assertion, remember to call as() before the assertion!assertThat(frodo.getAge()).as("check %s's age", frodo.getName()) .isEqualTo(100);
错误消息样式:
[check Frodo's age] expected:<100> but was:<33>
结语
AssertJ提供了比TestNG更丰富断言语句,快来体验一下吧。
参考
https://assertj.github.io/doc/
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!