在模拟框架中进行模拟与间谍活动 [英] Mocking vs. Spying in mocking frameworks

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

问题描述

在模拟框架中,您可以模拟一个对象或间谍.两者之间有什么区别?何时/应该何时使用另一种?

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 为例,我发现使用 spies 和 mocks ,但是我不确定两者之间的区别.

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:

您可以创建真实对象的间谍.当您使用间谍时,将调用 real 方法(除非对某个方法进行了打桩).

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天全站免登陆