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.


    public class Sample{
        DependencyOne dependencyOne;
        DependencyTwo dependencyTwo;

        public SampleResponse methodOfSample(){


            return sampleResponse;

Junit Test Case

public class SampleTest{

    Sample sample;

    DependencyOne dependencyOne;

    DependencyTwo dependencyTwo;

    public void init() {

    public void sampleMethod1_Test(){
        //Arrange the dependencies
        DependencyResponse dependencyOneResponse = Mock(sampleResponse.class);

        DependencyResponse dependencyTwoResponse = Mock(sampleResponse.class);

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

        <assert the SampleResponse here>