Using @InjectMocks annotation

In this post under Mockito, I will show with example the purpose of “@InjectMocks” annotation.

In the previous post, I showed with example, the purpose of “@Mock” annotation.

For recap “@Mock” annotation is used to instruct Mockito framework to create a mock of an object and assign it to variable.

We write unit test class to test the main class logic.

The main class that is under test depends on other classes to perform there job.

The class under test becomes the dependee, whereas the classes that dependee depends upon become dependents.

So to test the dependee we need to create mock of those dependent objects.

We can use “@Mock” annotation to create mock of those dependent objects.

But we need to inject those mock objects into dependee, so that we can test the dependee.

We need to tell Mockito framework which is the dependee.

So for that we use the “@InjectMocks” annotation.

We annotate it on a field.

Once we annotate the dependee with “@InjectMocks” annotation, the Mockito framework will create a mock of dependent objects and inject them into dependee properties.

Let see an example.

For our example, I will two classes “PersonDAO” and “PersonManager”. Below are the class structure

PersonDAO

package package3;
public class PersonDAO {
}

PersonManager

package package3;
public class PersonManager {
private PersonDAO personDAO;
public PersonDAO getPersonDAO() {
return personDAO;
}
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
}

For our example, we need to test “PersonManager”, so it becomes dependee and “PersonDAO” becomes dependents.

Below is the test class

package package3;
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;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(MockitoExtension.class)
public class PersonManagerTest {
@InjectMocks
private PersonManager personManager;
@Mock
private PersonDAO personDAO;
@Test
public void test() {
assertNotNull(personManager.getPersonDAO());
}
}

In the above test class, at line 14 I declare a field by name “personManager” of type “PersonManager” and annotate it with “@InjectMocks” annotation. This tells Mockito framework that “personManager”
is dependee and it has to find all the fields declared with “@Mock” annotation and inject them as dependents in dependee.

At line 17, we declare a field by name “personDAO” of type “PersonDAO” and annotate it with “@Mock” annotation. This tells Mockito framework to create a mock of “PersonDAO” and assign it to that variable.

In this way, we use “@InjectMocks” annotation.

Leave a comment