This article looks at injecting mock dependencies into the classes you want to test. For the examples below we use Mockito and Junit.
To inject mocks into your test class, you will need to include the following two dependencies:
The dependencies for Mockito:
The Mockito dependencies that uses JUnit APIs to initiate mocks.
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:
This is the class we want to test inside the test class:
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
@InjectMocks annotated fields.
@ExtendWith(MockitoExtension.class) inplace Mockito will initialize the
@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:
- Constructor injection
- Property setting injection
- Field injection
The test class using @InjectMocks:
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.
More about testing in Java: