AssertJ’s Java 8 Features – AssertJ的Java 8功能

最后修改: 2016年 7月 12日

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

1. Overview

1.概述

This article focuses on AssertJ‘s Java8-related features and is the third article from the series.

本文重点介绍AssertJ的Java8相关功能,是该系列文章的第三篇。

If you’re looking for general information on its main features have a look at the first article in the series Introduction to AssertJ and then at AssertJ for Guava.

如果你正在寻找关于其主要功能的一般信息,请看系列文章AssertJ简介,然后是Guava的AssertJ

2. Maven Dependencies

2.Maven的依赖性

Java 8’s support is included in the main AssertJ Core module since version 3.5.1. In order to use the module, you will need to include the following section in your pom.xml file:

自3.5.1版以来,Java 8的支持包含在主AssertJ核心模块中。为了使用该模块,你需要在你的pom.xml文件中包括以下部分。

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

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

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

The latest Core version can be found here.

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

3. Java 8 Features

3.Java 8的特点

AssertJ leverages Java 8 features by providing special helper methods and new assertions for Java 8 types.

AssertJ通过为Java 8类型提供特殊的辅助方法和新的断言,充分利用了Java 8的特性。

3.1. Optional Assertions

3.1.可选的断言

Let’s create a simple Optional instance:

让我们创建一个简单的Optional实例。

Optional<String> givenOptional = Optional.of("something");

We can now easily check if an Optional contains some value and what that containing value is:

我们现在可以很容易地检查一个Optional是否包含某些值,以及该包含值是什么。

assertThat(givenOptional)
  .isPresent()
  .hasValue("something");

3.2. Predicate Assertions

3.2.谓词断言

Let’s create a simple Predicate instance by checking the length of a String:

让我们通过检查String的长度来创建一个简单的Predicate实例。

Predicate<String> predicate = s -> s.length() > 4;

Now you can easily check which Strings are rejected or accepted by the Predicate:

现在你可以轻松地检查哪些字符串谓词拒绝或接受:

assertThat(predicate)
  .accepts("aaaaa", "bbbbb")
  .rejects("a", "b")
  .acceptsAll(asList("aaaaa", "bbbbb"))
  .rejectsAll(asList("a", "b"));

3.3. LocalDate Assertions

3.3.LocalDate断言

Let’s start by defining two LocalDate objects:

让我们从定义两个LocalDate对象开始。

LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
LocalDate todayDate = LocalDate.now();

You can now easily check if a given date is before/after a given date, or today:

现在你可以很容易地检查一个给定的日期是否在一个给定的日期之前/之后,或今天。

assertThat(givenLocalDate)
  .isBefore(LocalDate.of(2020, 7, 8))
  .isAfterOrEqualTo(LocalDate.of(1989, 7, 8));

assertThat(todayDate)
  .isAfter(LocalDate.of(1989, 7, 8))
  .isToday();

3.4. LocalDateTime Assertions

3.4.LocalDateTime断言

The LocalDateTime assertions work similarly to LocalDate‘s, but do not share the isToday method.

LocalDateTime断言的工作方式与LocalDate类似,但不共享isToday方法。

Let’s create an example LocalDateTime object:

让我们创建一个例子LocalDateTime对象。

LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);

And now you can check:

而现在你可以检查。

assertThat(givenLocalDate)
  .isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));

3.5. LocalTime Assertions

3.5.LocalTime断言

The LocalTime assertions work similarly to other java.util.time.* assertions, but they do have one exclusive method: hasSameHourAs.

LocalTime断言的工作方式与其他java.util.time.*断言类似,但它们确实有一个专属方法。hasSameHourAs.

Let’s create an example LocalTime object:

让我们创建一个LocalTime对象的例子。

LocalTime givenLocalTime = LocalTime.of(12, 15);

and now you can assert:

而现在你可以断言。

assertThat(givenLocalTime)
  .isAfter(LocalTime.of(1, 0))
  .hasSameHourAs(LocalTime.of(12, 0));

3.6. FlatExtracting Helper Method

3.6.FlatExtractingHelper方法

The FlatExtracting is a special utility method that utilizes Java 8’s lambdas in order to extract properties from Iterable elements.

FlatExtracting是一个特殊的实用方法,它利用Java 8的lambdas,以便从 Iterable元素中提取属性

Let’s create a simple List with LocalDate objects:

让我们用LocalDate对象创建一个简单的List

List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));

now we can easily check if this List contains at least one LocalDate object with the year 2015:

现在我们可以很容易地检查这个List是否至少包含一个2015年的LocalDate对象。

assertThat(givenList)
  .flatExtracting(LocalDate::getYear)
  .contains(2015);

the flatExtracting method does not limit us to field extraction. We can always provide it with any function:

flatExtracting方法并不限制我们进行字段提取。我们总是可以为它提供任何功能。

assertThat(givenList)
  .flatExtracting(LocalDate::isLeapYear)
  .contains(true);

or even:

或甚至。

assertThat(givenList)
  .flatExtracting(Object::getClass)
  .contains(LocalDate.class);

You can also extract multiple properties at once:

你还可以一次提取多个属性。

assertThat(givenList)
  .flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
  .contains(2015, 6);

3.7. Satisfies Helper Method

3.7.满足帮助方法

The Satisfies method allows you to quickly check if an object satisfies all provided assertions.

Satisfies方法允许你快速检查一个对象是否满足所有提供的断言。

Let’s create an example String instance:

让我们创建一个String实例。

String givenString = "someString";

and now we can provide assertions as a lambda body:

而现在我们可以把断言作为lambda主体来提供。

assertThat(givenString)
  .satisfies(s -> {
    assertThat(s).isNotEmpty();
    assertThat(s).hasSize(10);
  });

3.8. HasOnlyOneElementSatisfying Helper Method

3.8.HasOnlyOneElementSatisfying帮助方法

The HasOnlyOneElement helper method allows checking if an Iterable instance contains exactly only one element satisfying provided assertions.

HasOnlyOneElement辅助方法允许检查Iterable实例是否正好只包含一个满足所提供断言的元素。

Let’s create an example List:

让我们创建一个例子List:

List<String> givenList = Arrays.asList("");

and now you can assert:

而现在你可以断言。

assertThat(givenList)
  .hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());

3.9. Matches Helper Method

3.9.Matches帮助方法

The Matches helper method allows checking if a given object matches the given Predicate function.

Matches辅助方法允许检查一个给定的对象是否与给定的Predicate函数相匹配。

Let’s take an empty String:

让我们取一个空的字符串:

String emptyString = "";

and now we can check it’s state by providing an adequate Predicate lambda function:

而现在我们可以通过提供一个适当的Predicate lambda函数来检查它的状态。

assertThat(emptyString)
  .matches(String::isEmpty);

4. Conclusion

4.结论

In this last article from the AssertJ series, we explored all advanced AssertJ Java 8’s features, which concludes the series.

在AssertJ系列的最后一篇文章中,我们探讨了AssertJ Java 8的所有高级功能,这也是该系列的结束。

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

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

Next »

Custom Assertions with AssertJ

« Previous

AssertJ for Guava