@Mock and @InjectMocks are Mockito annotations that reduce test boilerplate by automatically creating mock dependencies and wiring them into the class under test.
Key Points: • @Mock replaces manual mock(SomeType.class) calls with a field-level annotation. • @InjectMocks creates an instance of the annotated class and injects any matching @Mock fields into it, via constructor, setter, or field injection. • Both require initialization, either through @ExtendWith(MockitoExtension.class) in JUnit 5 or MockitoAnnotations.openMocks(this) in setup. • Constructor injection is Mockito's preferred strategy for @InjectMocks since it's the most reliable and explicit. • If a dependency can't be matched or the constructor is ambiguous, @InjectMocks silently leaves it null, which can cause confusing NullPointerExceptions.
Example: For a class OrderService(PaymentGateway gateway), declaring @Mock PaymentGateway gateway and @InjectMocks OrderService orderService lets Mockito construct orderService with the mocked gateway automatically, no manual wiring required.
Interview Tip: A concise interview answer is:
"@Mock creates a mock dependency without calling mock() manually, and @InjectMocks creates the class under test and automatically injects any matching @Mock fields into it, usually via its constructor. Together they cut down boilerplate setup code in every test class."