Video in progress
How do the @Mock and @InjectMocks annotations differ?
@Mock creates a fake object for a dependency. @InjectMocks creates an instance of the real class under test and places the mocks from the test class into it, through the constructor, a setter or a field.
📖 Answer
@ExtendWith(MockitoExtension.class)
class InvoiceServiceTest {
@Mock InvoiceRepository repository; // fake
@Mock TaxCalculator tax; // fake
@InjectMocks InvoiceService service; // real, with the mocks above inside
@Test
void soliq_qoshiladi() {
when(tax.rate()).thenReturn(new BigDecimal("0.12"));
// service runs its real code
}
}
Without @ExtendWith(MockitoExtension.class) the annotations don't work: the fields stay null and you get an NPE. This is the most common mistake among juniors.
@InjectMocks has one bad side: if it can't find a matching dependency, it stays silent and leaves the field null. That's why many experienced developers skip it and write new InvoiceService(repository, tax) themselves. If the constructor changes, the compiler tells you immediately.
Sign up to mark studied questions and save your progress.