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>
|
- 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.
- Mockito-core contains everything you need to create mocks inside your tests.
- 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:
Join the discussion: follow me on Twitter and share your thoughts
This post is just the beginning. If you're interested in learning more, be sure to follow me on
Twitter . And if you have
any questions or ideas, don't hesitate to reach out via
Twitter or
send me an email. I'm always happy to connect and continue the conversation.