Video in progress
How would you explain the difference between a mock, a stub, a spy and a fake?
A stub only returns a canned answer, while a mock also lets you verify calls. A spy wraps a real object and replaces some of its methods. A fake is a simplified but working implementation, for example an in-memory repository.
📖 Answer
Their common name is "test double", like a stunt double in a movie: it stands in for the real object.
| Kind | What it does | Example |
|---|---|---|
| Stub | gives a canned answer when asked | when(rates.usd()).thenReturn(12650) |
| Mock | answers + records the calls | verify(sms).send(...) |
| Spy | a real object with some methods replaced | spy(new ArrayList<>()) |
| Fake | has its own simple logic | InMemoryUserRepository (on top of a HashMap) |
In Mockito, a stub and a mock are the same object: one created with mock() can be both stubbed and verified. The difference is in how you use it.
Fakes are underrated. If you write a HashMap-based fake for a repository, you don't repeat when(...).thenReturn(...) in dozens of tests, and the tests aren't tied to implementation details. But a fake can have bugs too, so it has to be very simple.
Use a spy carefully: if you feel you need one, it often means the class is doing too much.
Sign up to mark studied questions and save your progress.