by BehindJava

What is the difference between @Mock and @InjectMocks

Home » java » What is the difference between @Mock and @InjectMocks

In this blog, we are going to learn the differences between @Mock and @InjectMocks.

@Mock vs @InjectMocks

MockitoAnnotations.initMocks(this) call, resets testing object and re-initializes mocks, so remember to have this at your @Before / @BeforeMethod annotation. The @InjectMocks annotation tries to instantiate the testing object instance and injects fields annotated with @Mock or @Spy into private fields. There are many different mocking frameworks in the Java space, however there are essentially two main types of mock object frameworks.

  • For the classes you require, @Mock generates a mock implementation.
  • When a class instance is created, @InjectMock injects the mocks that are annotated with @Mock into it.

Example

    public class Sample{
        DependencyOne dependencyOne;
        DependencyTwo dependencyTwo;


        public SampleResponse methodOfSample(){
            dependencyOne.methodOne();
            dependencyTwo.methodTwo();

            ...

            return sampleResponse;
        }
    }

Junit Test Case

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassA.class})
public class SampleTest{

    @InjectMocks
    Sample sample;

    @Mock
    DependencyOne dependencyOne;

    @Mock
    DependencyTwo dependencyTwo;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    public void sampleMethod1_Test(){
        //Arrange the dependencies
        DependencyResponse dependencyOneResponse = Mock(sampleResponse.class);
        Mockito.doReturn(dependencyOneResponse).when(dependencyOne).methodOne();

        DependencyResponse dependencyTwoResponse = Mock(sampleResponse.class);
        Mockito.doReturn(dependencyOneResponse).when(dependencyTwo).methodTwo();

        //call the method to be tested
        SampleResponse sampleResponse = sample.methodOfSample() 

        //Assert
        <assert the SampleResponse here>
    }
}