Third-party assertion libraries

As we have seen, the built-in assertions provided out of the box for Jupiter are sufficient for many testing scenarios. Nevertheless, there are times when more additional functionality, such as matchers, can be desired or required. In such situations, the JUnit team recommends the use of the following third-party assertion libraries:

In this section, we are going to make a brief review of Hamcrest. This library provided the assertion assertThat, which allows to create readable highly configurable assertions. The method assertThat accepts two arguments: first the actual object, and second a Matcher object. This matcher implements the interface org.hamcrest.Matcher, and enables a partial or an exact match for an expectation. Hamcrest provides different matcher utilities, such as is, either, or, not, and hasItem. The Matcher methods use the builder pattern, allowing to combine one or more matchers to build a matcher chain.

In order to use Hamcrest, first we need to import the dependency in our project. In a Maven project, this means that we have to include the following dependency in our pom.xml file:

<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>

If we are using Gradle, we need to add the equivalent configuration within the build.gradle file:

dependencies {
testCompile("org.hamcrest:hamcrest-core:${hamcrest}")
}
As usual, it is recommended using the latest version of Hamcrest. We can check it on the Maven central web (http://search.maven.org/).

The following example demonstrates how to use Hamcrest inside a Jupiter test. Concretely, this test uses the assertion assertThat together with the matchers containsString, equalTo, and notNullValue:

package io.github.bonigarcia;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestTest {

@Test
void assertWithHamcrestMatcher() {
assertThat(2 + 1, equalTo(3));
assertThat("Foo", notNullValue());
assertThat("Hello world", containsString("world"));
}

}

As shown in the following screenshot, this test is executed with no failure:

Console output of example using the Hamcrest assertion library
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.176.80