What is Mockito used for in tests?
Options
- Running the application in a production environment
- Creating mocks for dependencies to test a class alone (Correct option)
- Compiling Java source files into bytecode quickly
- Managing database schema migrations between versions
Answer
Creating mock objects that stand in for real dependencies, so you test one class in isolation and verify its interactions
Why
Mockito creates fake versions of your dependencies. You tell the mock what to return (when(...).thenReturn(...)) and later verify calls (verify(...)).
This lets you test OrderService without a real database or payment provider.
With JUnit 5: @ExtendWith(MockitoExtension.class), @Mock for fakes and @InjectMocks for the class under test.
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;
@Test
void chargesTheCustomer() {
when(gateway.charge(100)).thenReturn(true);
assertTrue(service.pay(100));
verify(gateway).charge(100);
}
}Remember
Mockito = fake dependencies for isolated unit tests.