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.
To use Mockito and JUnit you need to include the following three dependencies in your pom.xml:
- 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.
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:
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.
More about testing in Java: