unit-testingmockingtdd

Mocking vs. Spying in mocking frameworks


In mocking frameworks, you can mock an object or spy on it. What's the difference between the two and when would/should I use one over the other?

Looking at Mockito, for example, I see similar things being done using spies and mocks, but I am unsure as to the distinction between the two.


Solution

  • Mock object replace mocked class entirely, returning recorded or default values. You can create mock out of "thin air". This is what is mostly used during unit testing.

    When spying, you take an existing object and "replace" only some methods. This is useful when you have a huge class and only want to mock certain methods (partial mocking). Let me quote Mockito documentation:

    You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

    Real spies should be used carefully and occasionally, for example when dealing with legacy code.

    When in doubt, use mocks.