Contents

Mockito with JUnit 5

Writen by: David Vlijmincx

Introduction

In this post, I will show you how to use the Mockito extension with JUnit 5. You don't have to use the Mockito extension for JUnit, but with the extension included in your dependencies mocking becomes much easier to do. The extension allows you for example, to use @Mock and @InjectMock.

Dependencies

To use Mockito and JUnit you need to include the following three dependencies in your pom.xml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.9.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>5.2.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>
  1. The junit-jupiter dependency includes the transitive dependencies: junit-jupiter-api, junit-jupiter-params, and unit-jupiter-engine. You need these dependencies to write all kinds of unit tests.
  2. Mockito-core contains everything you need to create mocks inside your tests.
  3. mockito-junit-jupiter offers support for JUnit 5 extension model.

Creating a simple test

To check if everything works you can run the following test that uses Mockito and JUnit 5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package org.example;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class MainTest {

    @Mock
    TestMocking testMocking;

    @Test
    void testMain() {
        // test code
    }

}

class TestMocking { }

Using the Mockito extension for Junit 5 you can create a mock instance of a class using the @Mock annotation like is done on line 12 in the previous example.

Running test with Maven

To run your JUnit 5 unit tests with Maven you need to this plugin in your pom.xml:

1
2
3
4
5
6
7
8
9
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0</version>
        </plugin>
    </plugins>
</build>

Conclusion

We looked at all the steps needed to use the Mockito extension with JUnit 5 @ExtendWith annotation. This lets you create mocks using annotations like @Mock.

Further reading

More about testing in Java: