Contents

Inject Mock dependencies with Mockito

Writen by: David Vlijmincx

Introduction

This article looks at injecting mock dependencies into the classes you want to test. For the examples below we use Mockito and Junit.

Setup dependencies

To inject mocks into your test class, you will need to include the following two dependencies:

The dependencies for Mockito:

1
2
3
4
5
6
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>5.0.0</version>
    <scope>test</scope>
</dependency>

The Mockito dependencies that uses JUnit APIs to initiate mocks.

1
2
3
4
5
6
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>5.0.0</version>
    <scope>test</scope>
</dependency>

Setup of the classes we want to test

For this example, we have a Controller class that uses field injection to obtain an instance of the repository class.

This is the repository we want to mock inside the controller class:

1
2
3
@Stateless
public class Repository {
}

This is the class we want to test inside the test class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Controller {

    @Inject
    Repository repository;

    Controller(){

    }
    
    // code using the repository 
}

Using @Mock with @InjectMock

The following example is the test class we will use to test the Controller. We annotate the test class with @ExtendWith(MockitoExtension.class) to extend JUnit with Mockito. The extension will initialize the @Mock and @InjectMocks annotated fields.

with the @ExtendWith(MockitoExtension.class) inplace Mockito will initialize the @Mock and @InjectMocks annotated fields for us. The controller class uses field injection for the repository field. Mockito will do the same. Mockito can also do constructor and field injection.

The injection order is as follows:

  1. Constructor injection
  2. Property setting injection
  3. Field injection

The test class using @InjectMocks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class TestClass {

    @Mock
    Repository repository;

    @InjectMocks
    Controller controller;
    
    @Test
    void yourTestMethod(){
        // your testing code
    }

}

Conclusion

This post looked at all the steps necessary to use @Mock and @InjectMocks with JUnit. This was followed by an an example that uses the annotations to inject a mock dependency into the test class.

If you are curious and want to know more about what you can do with Mockito, please check out their documentation https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html. It lists all the Mockito features and how to use them.

Further reading

More about testing in Java: