Mockito: Mocks, Stubs and Spies

Learn
2 min readSep 10, 2024

--

Stubbing techniques are used to enforce predefined behavior.

when(somemock).methodOne(argOne).thenReturn(123); 

The above is stubbing. somemock is destined to behave in this way and only this way.

Mock
Mocks essentially detach all external dependencies from the class. When you create a mock for a class, a mock instance is created. The mockery is that the interface would be the same but there would be absolutely no functionality of the class which you just mocked.

  • Mocks are recording interactions when you call the method that you are interested in, the protagonist method, which in turn calls various instances within which are mocked. As the execution progresses from your method through each of the mocked dependencies and back, these mocks are recording the interactions.
  • Mocks then validate the expected behavior. And then you as the programmer can use mocks to validate the expected behavior. That is, this particular mocked method within this particular mocked instance was called so many times with these these kinds of arguments.
  • Mocks can also be made to throw exceptions. That is while stubbing the methods on the mock, you can also say that this mocked method throws so and so exception. And then you can validate that your protagonist method handles this exception in the right way.

Once you understand all that, and you have the tool of a mock in your testing armor, to create an mock instance, all you need to write is mock(myInstance)

Mockito does have a pretty clean API to work with.

Spy

Spy is a wrapper over the real object, that has spying abilities, to spy on what methods are invoked on the real object. Mock is just a scaffolding of the real object with no real object underneath — traditionally. Spy has the underlying real object.

  • Records activates
  • Validates behavior
  • Instantiated using spy(realInstance)

Stubbing a spy and a mock
Stubbing, by the literal meaning is about how the stub is not the real thing, and just what remains of the real object, as in a cigarette stub, or a ticket stub.
In the context of writing tests, stubbing is usually referred in the sense of enforcing a pre-determined behavior.
You can stub a mock.
You can stub a spy as well.

Mock and Spy are your raw material. Stubbing is where you come in. You decide what to stub so that you validate something else, and then in another test, you stub something else and validate this. Stubbing is where the story line is created. Mocks are Spies are your characters.

The action of stubbing is more relevant than the stub that you ended with.

--

--