Inject Mock object using @InjectMocks annotation of Mockito

In the previous tutorial, we passed the Mock object to the class which we are writing the Unit Test using the Setter method of this class. However, in case you are using the Spring framework in your application, the dependent objects are injected into the object we are writing Unit Test using the @Autowire annotation, so we will not have Setter methods for passing Mock objects. In this case, you can use @InjectMocks annotation of Mockito to do this. How is it in details? We will learn together in this tutorial!

First, I will create a Maven project:

Inject Mock object using @InjectMocks annotation of Mockito

with Spring framework, Mockito and JUnit dependencies as follows:

With JUnit 5, to run Unit Test with Maven, we need to declare the maven-surefire-plugin plugin of Maven with the latest version as follows:

And compile source with target using Java 8 onwards:

In the example of this tutorial, I am going to create a small application with a Calculation class that defines a method for calculating the subtraction of two numbers, declared with the @Component annotation of Spring as follows:

And an Application class defines a method that uses the method of class Calculation to calculate the subtraction of two numbers, if the result is greater than 0 then returns true, otherwise false. This class injects the object bean of the Calculation class using the Spring @Autowire annotation and is declared with the @Service annotation as follows:

with Spring’s configuration file located in the src/main/resources directory with the following contents:

Result:

Inject Mock object using @InjectMocks annotation of Mockito

Now, we will write Unit Test for the Application class!

Because currently, the class Application does not have a Setter method for the Calculation object, I will use Mockito’s @InjectMocks annotation to inject this object into the Application class as follows:

As you can see, I have declared using the Application class with @InjectMocks annotation. This declaration will allow us to inject all objects declared with the @Mock annotation in the ApplicationTest class into the Application object, here is the Calculation class.

If you now run Maven test then you will see the following result:

Inject Mock object using @InjectMocks annotation of Mockito

Add Comment