Video in progress
What is a mock object in a test, and why do you need one?
A mock is a fake object put in place of a real dependency: in the test you decide what it returns, and afterwards you can check how it was called. You need it to isolate things that are slow or that you can't control, like a database or an external API.
📖 Answer
Say OrderService saves an order and sends an SMS. In a unit test you don't want a real SMS going out, and you don't want to bring up a database either.
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock OrderRepository repository;
@Mock SmsClient sms;
@InjectMocks OrderService service;
@Test
void buyurtma_saqlansa_sms_ketadi() {
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
service.place(new Order("998901234567", 120_000));
verify(sms).send(eq("998901234567"), anyString());
}
}
What a mock helps with:
- it makes the test fast and stable: no network, no database;
- it makes hard situations easy to build: "the SMS service threw an exception" is hard to reproduce with a real service, and with a mock it's one line;
- it lets you check calls whose result you can't see (sending a message, logging).
But mocking everything is a mistake too; we'll call that "over-mocking" later.
Sign up to mark studied questions and save your progress.