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:
- Hamcrest (http://hamcrest.org/): an assertion framework to write matcher objects allowing rules to be defined declaratively.
- AssertJ (http://joel-costigliola.github.io/assertj/): fluent assertions for Java.
- Truth (https://google.github.io/truth/): an assertions Java library designed to make test assertions and failure messages more readable.
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}")
}
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: