In this short tutorial, we’re going to explore how to use JUnit 5 and Mockito, a popular mocking framework for unit tests written in Java.

1. JUnit 5 and Mockito Dependencies

1.1. Maven Dependencies

At first, let’s take a look at the Maven dependencies for JUnit 5:

Next, we’re going to include Mockito’s mockitojunitjupiter, an official support from the Mockito for JUnit 5:

1.2. Gradle Dependencies

Here is how our Gradle build file looks like:

2. JUnit 5 and Mockito Example

Let’s see an example test class that we use Mockito with JUnit 5:

We need to get the Mockito extension MockitoExtension for JUnit 5 enabled:

It initializes mocks and handles strict stubbings. And now we have all the Mockito annotations ready to work, for example:

We have used @Mock annotation to create a mock implementation for the UserManager interface we need.

Notice that the JUnit 5 extension Mockito by default works in the “strict mode”. To change the default behavior, we can use @MockitoSettings annotation as follows:

3. Conclusion

The tutorial has illustrated how to use Mockito with JUnit5 using official extension supported from Mockito. It’s really nice to use mock objects with JUnit 5.

The sample source code presented in the tutorial is available on my Github project. It’s a Maven based project, so it’s easy to be imported in IDE such as Eclipse, IntelliJ.

The tutorial is a part of JUnit 5 series. If you want to dig deeper and learn other cool things you can do with the JUnit 5 – head on over to the main JUnit 5 tutorial.

 

4 1 vote
Article Rating