Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Hamcrest with JUnit 5 when JUnit 5 doesn't have an assertThat() function?

To use Hamcrest with JUnit 4 we use an assertThat() function. However, JUnit 5 is no longer going to have an assertThat() function. How do I use Hamcrest without an assertThat()?

like image 871
Max Avatar asked Apr 07 '17 14:04

Max


People also ask

Does JUnit include Hamcrest?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

Which assertion API does not offer assertThat ()?

Assertions class does not provide an assertThat() method like the one found in JUnit 4's org. junit. Assert class which accepts a Hamcrest Matcher . Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Is assertThat deprecated?

assertThat method is deprecated. Its sole purpose is to forward the call to the MatcherAssert. assertThat defined in Hamcrest 1.3. Therefore, it is recommended to directly use the equivalent assertion defined in the third party Hamcrest library.


2 Answers

You have to make sure Hamcrest is included in the classpath and then use the assertThat() function provided by Hamcrest. From the current JUnit 5 User Guide - Writing Tests Assertions,

JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

The following example demonstrates how to use the assertThat() support from Hamcrest in a JUnit Jupiter test. As long as the Hamcrest library has been added to the classpath, you can statically import methods such as assertThat(), is(), and equalTo() and then use them in tests like in the assertWithHamcrestMatcher() method below.

import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat;  import org.junit.jupiter.api.Test;  class HamcrestAssertionDemo {      @Test     void assertWithHamcrestMatcher() {         assertThat(2 + 1, is(equalTo(3)));     }  } 

Naturally, legacy tests based on the JUnit 4 programming model can continue using org.junit.Assert#assertThat."

like image 84
Max Avatar answered Oct 24 '22 01:10

Max


See https://github.com/junit-team/junit5/issues/147:

you can use both, Hamcrest and AssertJ, in JUnit5. Both frameworks have a simple assertThat method, that you can import and use if wanted.

Currently, we do not plan to support these frameworks within our own Assertions to avoid the dependencies. Still, one can use them very well.

like image 45
Grigory Kislin Avatar answered Oct 24 '22 01:10

Grigory Kislin