Mocking vs. Spying in mocking frameworks

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.

Leave a Comment