Introduction to AssertJ – AssertJ简介

最后修改: 2016年 6月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article we will be exploring AssertJ – an opensource community-driven library used for writing fluent and rich assertions in Java tests.

在本文中,我们将探讨AssertJ – 一个开源的社区驱动库,用于在Java测试中编写流畅而丰富的断言。

This article focuses on tools available in the basic AssertJ module called AssertJ-core.

本文重点介绍基本AssertJ模块中的工具,称为AssertJ-core

2. Maven Dependencies

2.Maven依赖性

In order to use AssertJ, you need to include the following section in your pom.xml file:

为了使用AssertJ,你需要在你的pom.xml文件中包括以下部分。

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.4.1</version>
    <scope>test</scope>
</dependency>

This dependency covers only the basic Java assertions. If you want to use advanced assertions, you will need to add additional modules separately.

这个依赖性只包括基本的Java断言。如果你想使用高级断言,你将需要单独添加额外的模块。

Note that for Java 7 and earlier you should use AssertJ core version 2.x.x.

注意,对于Java 7和更早的版本,你应该使用AssertJ核心版本2.x.x。

Latest versions can be found here.

最新版本可以在这里找到。

3. Introduction

3.简介

AssertJ provides a set of classes and utility methods that allow us to write fluent and beautiful assertions easily for:

AssertJ提供了一组类和实用方法,使我们能够轻松地编写流畅和漂亮的断言。

  • Standard Java
  • Java 8
  • Guava
  • Joda Time
  • Neo4J and
  • Swing components

A detailed list of all modules is available on project’s website.

所有模块的详细清单可在项目的网站上查阅。

Let’s start with a few examples, right from the AssertJ’s documentation:

让我们从AssertJ的文档中的几个例子开始。

assertThat(frodo)
  .isNotEqualTo(sauron)
  .isIn(fellowshipOfTheRing);

assertThat(frodo.getName())
  .startsWith("Fro")
  .endsWith("do")
  .isEqualToIgnoringCase("frodo");

assertThat(fellowshipOfTheRing)
  .hasSize(9)
  .contains(frodo, sam)
  .doesNotContain(sauron);

The above examples are only the tip of the iceberg, but give us an overview of how writing assertions with this library might look like.

上面的例子只是冰山一角,但让我们对用这个库写断言的情况有了一个大概的了解。

4. AssertJ in Action

4.AssertJ在行动中

In this section we’ll focus on setting up AssertJ and exploring its possibilities.

在这一节中,我们将侧重于设置AssertJ并探索其可能性。

4.1. Getting Started

4.1.起步

With the jar of the library on a classpath, enabling assertions is as easy as adding a single static import to your test class:

有了classpath上的库的jar,启用断言就像给你的测试类添加一个静态导入一样容易。

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

4.2. Writing Assertions

4.2.编写断言

In order to write an assertion, you always need to start by passing your object to the Assertions.assertThat() method and then you follow with the actual assertions.

为了写一个断言,你总是需要先把你的对象传给Assertions.assertThat()方法,然后你再接着写实际断言。

It’s important to remember that unlike some other libraries, the code below does not actually assert anything yet and will never fail a test:

重要的是要记住,与其他一些库不同,下面的代码实际上还没有断言任何东西,并且永远不会测试失败。

assertThat(anyRefenceOrValue);

If you leverage your IDE’s code completion features, writing AssertJ assertions becomes incredibly easy due to its very descriptive methods. This is how it looks like in IntelliJ IDEA 16:

如果你利用你的IDE的代码完成功能,由于AssertJ的描述性方法,编写AssertJ断言变得非常容易。这是它在IntelliJ IDEA 16中的样子。

IDE's code completion features

IDE’s code completion features

IDE的代码完成功能

 

As you can see, you have dozens of contextual methods to choose from and those are available only for String type. Let’s explore in detail some of this API and look at some specific assertions.

正如你所看到的,你有几十种上下文方法可供选择,而这些方法只适用于String类型。让我们详细探讨一下这个API的一些内容,看看一些具体的断言。

4.3. Object Assertions

4.3.对象断言

Objects can be compared in various ways either to determine equality of two objects or to examine the fields of an object.

对象可以通过各种方式进行比较,要么确定两个对象的平等性,要么检查一个对象的字段。

Let’s look at two ways that we can compare the equality of two objects. Given the following two Dog objects fido and fidosClone:

让我们看一下我们可以比较两个对象的平等性的两种方法。给出以下两个Dog对象fidofidosClone

public class Dog { 
    private String name; 
    private Float weight;
    
    // standard getters and setters
}

Dog fido = new Dog("Fido", 5.25);

Dog fidosClone = new Dog("Fido", 5.25);

We can compare equality with the following assertion:

我们可以用下面的断言来比较平等。

assertThat(fido).isEqualTo(fidosClone);

This will fail as isEqualTo() compares object references. If we want to compare their content instead, we can use isEqualToComparingFieldByFieldRecursively() like so:

这将会失败,因为isEqualTo()比较的是对象引用。如果我们想比较它们的内容,我们可以像这样使用isEqualToComparingFieldByFieldRecursively()

assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);

Fido and fidosClone are equal when doing a recursive field by field comparison because each field of one object is compared to the field in the other object.

FidofidosClone在进行逐个字段的递归比较时是相等的,因为一个对象的每个字段都会与另一个对象的字段进行比较。

There are many other assertion methods that provide different ways to compare and contract objects and to examine and assert on their fields. In order to discover them all, refer to the official AbstractObjectAssert documentation.

还有许多其他的断言方法,它们提供了不同的方式来比较和收缩对象,并对它们的字段进行检查和断言。为了发现它们,请参考官方的AbstractObjectAssert 文档

4.4. Boolean Assertions

4.4.布尔断言

Some simple methods exist for truth testing:

有一些简单的方法可用于真理检验。

  • isTrue()
  • isFalse()

Let’s see them in action:

让我们看看他们的行动。

assertThat("".isEmpty()).isTrue();

4.5. Iterable/Array Assertions

4.5.Iterable/Array Assertions

For an Iterable or an Array there are multiple ways of asserting that their content exist. One of the most common assertions would be to check if an Iterable or Array contains a given element:

对于IterableArray,有多种方法可以断言其内容存在。最常见的断言之一是检查IterableArray是否包含一个指定的元素。

List<String> list = Arrays.asList("1", "2", "3");

assertThat(list).contains("1");

or if a List is not empty:

或如果一个List不是空的。

assertThat(list).isNotEmpty();

or if a List starts with a given character. For example “1”:

或如果一个List以一个给定的字符开始。例如 “1”。

assertThat(list).startsWith("1");

Keep in mind that if you want to create more than one assertion for the same object, you can join them together easily.

请记住,如果你想为同一个对象创建一个以上的断言,你可以很容易地把它们连接起来。

Here is an example of an assertion that checks if a provided list is not empty, contains “1” element, does not contains any nulls and contains sequence of elements “2”, “3”:

下面是一个断言的例子,它检查所提供的列表是否为空,包含 “1 “元素,不包含任何空值,并且包含 “2”、”3 “元素的序列。

assertThat(list)
  .isNotEmpty()
  .contains("1")
  .doesNotContainNull()
  .containsSequence("2", "3");

Of course many more possible assertions exist for those types. In order to discover them all, refer to the official AbstractIterableAssert documentation.

当然,对于这些类型还有许多可能的断言存在。为了发现它们,请参考官方的AbstractIterableAssert 文档

4.6. Character Assertions

4.6.角色断言

Assertions for character types mostly involve comparisons and even checking if a given character is from a Unicode table.

字符类型的断言大多涉及比较,甚至检查一个给定的字符是否来自Unicode表。

Here is an example of an assertion that checks if a provided character is not ‘a’, is in Unicode table, is greater than ‘b’ and is lowercase:

下面是一个断言的例子,它检查所提供的字符是否不是’a’,是否在Unicode表中,是否大于’b’并且是小写的。

assertThat(someCharacter)
  .isNotEqualTo('a')
  .inUnicode()
  .isGreaterThanOrEqualTo('b')
  .isLowerCase();

For a detailed list of all character types’ assertions, see AbstractCharacterAssert documentation.

关于所有字符类型的断言的详细列表,请参阅AbstractCharacterAssert 文档

4.7. Class Assertions

4.7.类断言

Assertions for Class type are mostly about checking its fields, Class types, presence of annotations and class finality.

Class类型的断言主要是检查其字段、Class类型、注释的存在和类的最终性。

If you want to assert that class Runnable is an interface, you need to simply write:

如果你想断言类Runnable是一个接口,你需要简单地写。

assertThat(Runnable.class).isInterface();

or if you want to check if one class is assignable from the other:

或者如果你想检查一个类是否可以从另一个类中分配。

assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);

All possible Class assertions can be viewed in the AbstractClassAssert documentation.

所有可能的断言都可以在AbstractClassAssert 文档中查看。

4.8. File Assertions

4.8.文件断言

File assertions are all about checking if a given File instance exists, is a directory or a file, has certain content, is readable, or has given extension.

文件断言是关于检查一个给定的文件实例是否存在,是一个目录还是一个文件,是否有某些内容,是否可读,或者是否有给定的扩展名。

Here you can see an example of an assertion that checks if a given file exists, is file and not a directory, can be readable and writable:

这里你可以看到一个断言的例子,它检查一个给定的文件是否存在,是否是文件而不是目录,是否可读和可写。

 assertThat(someFile)
   .exists()
   .isFile()
   .canRead()
   .canWrite();

All possible Class assertions can be viewed in the AbstractFileAssert documentation.

所有可能的类断言都可以在AbstractFileAssert 文档中查看。

4.9. Double/Float/Integer Assertions

4.9.Double/Float/Integer断言

Double/Float/Integer and Other Number Types

Double/Float/Integer和其他数字类型

Numeric assertions are all about comparing numeric values within or without a given offset. For example, if you want to check if two values are equal according to a given precision we can do the following:

数字断言都是在给定的偏移量内或不给定的偏移量内比较数值。例如,如果你想根据给定的精度检查两个数值是否相等,我们可以做以下工作。

assertThat(5.1).isEqualTo(5, withPrecision(1d));

Notice that we are using already imported withPrecision(Double offset) helper method for generating Offset objects.

注意,我们正在使用已经导入的withPrecision(Double offset)辅助方法来生成Offset对象。

For more assertions, visit AbstractDoubleAssert documentation.

关于更多的断言,请访问AbstractDoubleAssert 文档

4.10. InputStream Assertions

4.10.InputStream断言

There is only one InputStream-specific assertion available:

只有一个InputStream特定断言可用。

  • hasSameContentAs(InputStream expected)

and in action:

并在行动中。

assertThat(given).hasSameContentAs(expected);

4.11. Map Assertions

4.11.地图断言

Map assertions allow you to check if a map contains certain entry, set of entries, or keys/values separately.

Map断言允许你分别检查一个地图是否包含某些条目、条目集或键/值。

And here you can see an example of an assertions that checks if a given map is not empty, contains numeric key “2”, does not contain numeric key “10” and contains entry: key: 2, value: “a”:

这里你可以看到一个断言的例子,它检查一个给定的地图是否为空,是否包含数字键 “2”,是否包含数字键 “10”,是否包含条目。键:2,值。”a”

assertThat(map)
  .isNotEmpty()
  .containsKey(2)
  .doesNotContainKeys(10)
  .contains(entry(2, "a"));

For more assertions, see AbstractMapAssert documentation.

有关更多断言,请参阅AbstractMapAssert 文档

4.12. Throwable Assertions

4.12.可抛出的断言

Throwable assertions allow for example: inspecting exception’s messages, stacktraces, cause checking or verifying if an exception has been thrown already.

可抛出断言允许例如:检查异常的消息、堆栈跟踪、原因检查或验证是否已经抛出了异常。

Let’s have a look at the example of an assertion that checks if a given exception was thrown and has a message ending with “c”:

让我们来看看一个断言的例子,它检查一个给定的异常是否被抛出,并且有一个以 “c “结尾的消息。

assertThat(ex).hasNoCause().hasMessageEndingWith("c");

For more assertions, see AbstractThrowableAssert documentation.

有关更多断言,请参见 AbstractThrowableAssert 文档

5. Describing Assertions

5.描述断言

In order to achieve even higher verbosity level, you can create dynamically generated custom descriptions for your assertions. The key to doing this is the as(String description, Object… args) method.

为了达到更高的粗制滥造水平,你可以为你的断言创建动态生成的自定义描述。这样做的关键是as(String description, Object… args) 方法。

If you define your assertion like this:

如果你这样定义你的论断。

assertThat(person.getAge())
  .as("%s's age should be equal to 100", person.getName())
  .isEqualTo(100);

this is what you will get when running tests:

这就是你在运行测试时将得到的结果。

[Alex's age should be equal to 100] expected:<100> but was:<34>

6. Java 8

6.JAVA 8

AssertJ takes full advantage of Java 8’s functional programming features. Let’s dive into an example and see it in action. First let’s see how we do it in Java 7:

AssertJ充分利用了Java 8的函数式编程特性。让我们深入到一个例子中,看看它的运行情况。首先让我们看看在Java 7中是如何做的。

assertThat(fellowshipOfTheRing)
  .filteredOn("race", HOBBIT)
  .containsOnly(sam, frodo, pippin, merry);

Here we are filtering a collection on the race Hobbit and in Java 8 we can do something like this:

在这里,我们正在过滤一个关于种族霍比特人的集合,在Java 8中,我们可以这样做。

assertThat(fellowshipOfTheRing)
  .filteredOn(character -> character.getRace().equals(HOBBIT))
  .containsOnly(sam, frodo, pippin, merry);

We will be exploring AssertJ’s Java8 capabilities in a future article from this series. The above examples were taken from AssertJ’s website.

我们将在本系列的未来文章中探讨AssertJ的Java8功能。上述例子取自AssertJ的网站

7. Conclusion

7.结论

In this article we briefly explored the possibilities that AssertJ gives us along with the most popular assertions for core Java types.

在这篇文章中,我们简要地探讨了AssertJ给我们带来的可能性,以及最流行的核心Java类型的断言。

The implementation of all the examples and code snippets can be found in a GitHub project.

所有例子和代码片段的实现都可以在GitHub项目中找到。

Next »

AssertJ for Guava