How to use Mockito with JUnit 5?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Mockito is a popular mocking framework used in conjunction with JUnit 5 for unit testing in Java applications. It simplifies the creation of testable code by allowing you to replace real objects with mock objects, isolating the unit under test. This article will guide you through using Mockito with JUnit 5 by covering setup, basic usage, and advanced features.
Setup
Before you can start using Mockito with JUnit 5, you need to add the libraries to your project. With Maven, you can include the following dependencies in your pom.xml:
Note: Versions are based on the latest releases as of this writing, and you should check for updates before proceeding.
Basic Usage
Creating Mocks
Mockito provides straightforward API methods to create and use mock objects:
Using Annotations
You can simplify the syntax with annotations provided by Mockito:
Argument Matchers
Mockito provides matchers to validate arguments when specifying behavior for mock methods:
Advanced Features
Stubbing with Custom Answers
You can customize the behavior of a mock method by using the Answer interface:
Capturing Arguments
To verify the arguments passed to the mock methods, you can use ArgumentCaptor:
Mocking Static Methods
With version 3.4.0 onwards, Mockito allows mocking static methods:
Key Points Summary
| Feature | Description | Example |
| Creating Mocks | To simulate behavior of objects | MyService myService = mock(MyService.class); |
| Using Annotations | Simplified syntax with @Mock and @InjectMocks | @Mock private MyService myService; |
| Argument Matchers | Allows flexibility in defining mock behavior | when(myService.getData(anyString())) |
| Custom Answer | Define dynamic behavior for mock methods | thenAnswer(invocation -> "Data"); |
| ArgumentCaptor | Capture arguments to validate in assertions | captor.capture() |
| Static Methods | Mock static methods (from version 3.4.0 onwards) | mockStatic(MyUtilityClass.class) |
Using Mockito with JUnit 5 enables concise and flexible unit tests by isolating components and mocking their dependencies. This approach helps improve test coverage, and test reliability, and reduce the complexity of the codebase, all crucial elements for maintainable software development.

