Mockito
JUnit 5
Unit Testing
Java
Testing Frameworks

How to use Mockito with JUnit 5?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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:

xml
1<dependencies>
2    <dependency>
3        <groupId>org.junit.jupiter</groupId>
4        <artifactId>junit-jupiter</artifactId>
5        <version>5.9.2</version>
6        <scope>test</scope>
7    </dependency>
8    <dependency>
9        <groupId>org.mockito</groupId>
10        <artifactId>mockito-core</artifactId>
11        <version>5.2.0</version>
12        <scope>test</scope>
13    </dependency>
14    <dependency>
15        <groupId>org.mockito</groupId>
16        <artifactId>mockito-junit-jupiter</artifactId>
17        <version>5.2.0</version>
18        <scope>test</scope>
19    </dependency>
20</dependencies>

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:

java
1import org.junit.jupiter.api.Test;
2import org.mockito.Mockito;
3
4import static org.mockito.Mockito.*;
5
6class MyClassTest {
7
8    @Test
9    void testMethod() {
10        // Create a mock instance of a class
11        MyService myService = mock(MyService.class);
12
13        // Define behavior for the mock
14        when(myService.getData()).thenReturn("Mock Data");
15
16        // Use the mock in tests
17        String result = myService.getData();
18
19        // Verify the method call
20        verify(myService).getData();
21
22        assertEquals("Mock Data", result);
23    }
24}

Using Annotations

You can simplify the syntax with annotations provided by Mockito:

java
1import org.junit.jupiter.api.BeforeEach;
2import org.junit.jupiter.api.Test;
3import org.mockito.InjectMocks;
4import org.mockito.Mock;
5import org.mockito.MockitoAnnotations;
6
7import static org.mockito.Mockito.*;
8
9class MyClassTest {
10
11    @Mock
12    private MyService myService;
13
14    @InjectMocks
15    private MyClass myClass;
16
17    @BeforeEach
18    void setUp() {
19        MockitoAnnotations.openMocks(this);
20    }
21
22    @Test
23    void testMethod() {
24        when(myService.getData()).thenReturn("Mock Data");
25
26        String result = myClass.useService();
27
28        verify(myService).getData();
29        assertEquals("Mock Data", result);
30    }
31}

Argument Matchers

Mockito provides matchers to validate arguments when specifying behavior for mock methods:

java
when(myService.getData(anyString())).thenReturn("Mock Data");

Advanced Features

Stubbing with Custom Answers

You can customize the behavior of a mock method by using the Answer interface:

java
1when(myService.getData(anyString())).thenAnswer(invocation -> {
2    String arg = invocation.getArgument(0);
3    return "Data for " + arg;
4});

Capturing Arguments

To verify the arguments passed to the mock methods, you can use ArgumentCaptor:

java
1import org.mockito.ArgumentCaptor;
2
3ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
4verify(myService).getData(captor.capture());
5
6String capturedArg = captor.getValue();
7assertEquals("Expected Arg", capturedArg);

Mocking Static Methods

With version 3.4.0 onwards, Mockito allows mocking static methods:

java
1import static org.mockito.Mockito.mockStatic;
2
3try (MockedStatic<MyUtilityClass> mockedStatic = mockStatic(MyUtilityClass.class)) {
4    mockedStatic.when(() -> MyUtilityClass.staticMethod()).thenReturn("Fake Response");
5
6    // Test your logic involving the static method
7}

Key Points Summary

FeatureDescriptionExample
Creating MocksTo simulate behavior of objectsMyService myService = mock(MyService.class);
Using AnnotationsSimplified syntax with @Mock and @InjectMocks@Mock private MyService myService;
Argument MatchersAllows flexibility in defining mock behaviorwhen(myService.getData(anyString()))
Custom AnswerDefine dynamic behavior for mock methodsthenAnswer(invocation -> "Data");
ArgumentCaptorCapture arguments to validate in assertionscaptor.capture()
Static MethodsMock 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.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.