W3docs

Difference between @Mock and @InjectMocks

In the context of testing with the Mockito framework, the @Mock annotation is used to create a mock object of a class or interface, and the @InjectMocks annotation is used to inject the mock objects into a test class.

In the context of testing with the Mockito framework, the @Mock annotation creates a mock object for a class or interface, while @InjectMocks creates an instance of a class and automatically injects those mocks into it. This example follows JUnit 5 standards.

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.mockito.Mockito.verify;

@ExtendWith(MockitoExtension.class)
class MyTestClassTest {

    @Mock
    private MyClass myClass;

    @InjectMocks
    private MyTestClass myTestClass;

    @Test
    void testMockInteraction() {
        myTestClass.doSomething();
        verify(myClass).someMethod();
    }
}

In this example, @Mock generates a mock instance of MyClass, and @InjectMocks instantiates MyTestClass while injecting the mock into it. When using JUnit 5, the MockitoExtension handles initialization automatically, so manual @BeforeEach setup or MockitoAnnotations.initMocks() is no longer required.

The verify() method confirms that someMethod() was called on the mock during the test, allowing you to isolate and validate the behavior of the class under test.