Java Mocks and test doubles

Mockito is easy to use and easy to overuse. The interesting question is always what should not be mocked.

3 concepts · 9 interview questions

What this topic covers

Every concept in mocks and test doubles, and the questions each one gets asked as. Where a question links, it has a full write-up.

Stubs, mocks, spies and fakes

They differ in what they replace and what they verify. A stub returns canned answers; a mock also asserts on the interaction; a fake is a working lightweight implementation.

  • What is the difference between a mock and a stub?
  • When would you use a fake instead of a mock?
  • What is a spy, and when is one justified?

What not to mock

Mocking a type you do not own bakes your assumptions about it into the test. When the real library behaves differently, the test still passes.

  • Why should you avoid mocking types you do not own?
  • Should you mock a repository or use an in-memory database?
  • What does it mean when a test needs five mocks?

Verifying interactions

Asserting that a collaborator was called ties the test to how the work is done rather than what it achieves, which is why such tests break on every refactor.

  • When is verifying a call the right assertion?
  • What is over-specification in a test?
  • Why do mock-heavy suites break on refactoring?

More in Testing

See the whole reference map →