SteelReed

Search

Search posts, questions…

TestingQuestion 3 / 9

Junior

How do mocks, stubs and spies differ when using Mockito?

Short answer

A stub returns canned data and you check the result. A mock lets you check whether it was called. A spy wraps a real object and overrides only a few methods.

Test doubleStub: when...thenReturncheck the resultMock: verifycheck interactionsSpy: wraps real objectoverrides some methods

3 points to say:

  1. Stubs use when...thenReturn; mocks are checked with verify.
  2. A spy calls real code; stub a spy with doReturn.
  3. Unused stubs raise UnnecessaryStubbingException.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.