Mocking vs. Spying in mocking frameworks

后端 未结 7 1293
执念已碎
执念已碎 2020-11-28 20:24

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?

7条回答
  •  不思量自难忘°
    2020-11-28 20:48

    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.

提交回复
热议问题