SoFunction
Updated on 2025-04-13

The difference and description of Mock and @InjectMocks

The difference between @Mock and @InjectMocks

@Mock and @InjectMocks are two annotations in the Mockito framework.

@Mock

  • Used to create mock objects, the attribute values ​​of the created mock objects are initialized with the default values. For example, int defaults to 0, boolean defaults to false, and null is initialized with reference data types.
  • This annotation creates a mock object that has the same behavior of the class being mocked and allows itself to define the return value and behavior of the method.

@InjectMocks

  • Used to inject mock objects into the corresponding field in the tested class
  • This annotation allows you to automatically inject mock objects into fields marked @InjectMocks in the tested class
  • It can be understood that the object created using @Mock is injected into the object created by @InjectMocks.
  • In this way, the tested class can use mock objects as its dependencies

Code Example

public class AClassTest{
    @Mock
    private AClass aClass;
    @Test
    public void testMethodA() {
        //Test using aClass    }
}

public class BClassTest{
    @Mock
    private AClass aClass;
    
    @InjectMocks
    private BClass bClass;
    
    @Test
    public void testMethodB() {
        // Use bClass for testing, where aClass has been injected into bClass    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.