模拟框架中的模拟与间谍 [英] Mocking vs. Spying in mocking frameworks

查看:26
本文介绍了模拟框架中的模拟与间谍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模拟框架中,您可以模拟一个对象或监视对象.两者之间有什么区别,我什么时候应该/应该使用一个而不是另一个?

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?

Mockito 为例,我看到使用 spiesmocks,但我不确定两者之间的区别.

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.

推荐答案

模拟对象完全替换模拟类,返回记录或默认值.您可以凭空"创建模拟.这是单元测试中最常用的.

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.

进行间谍活动时,您可以使用现有对象并替换"对象.只有一些方法.当您有一个庞大的类并且只想模拟某些方法(部分模拟)时,这很有用.让我引用 Mockito 文档:

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:

您可以创建真实对象的间谍.当你使用 spy 时,真正的方法被调用(除非一个方法被存根).

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.

这篇关于模拟框架中的模拟与间谍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆