模拟 & 和有什么不一样?存根? [英] What's the difference between a mock & stub?

查看:37
本文介绍了模拟 & 和有什么不一样?存根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过各种关于测试中模拟与存根的文章,包括 Martin Fowler 的 Mocks Aren't Stubs,但还是不明白区别.

I've read various articles about mocking vs stubbing in testing, including Martin Fowler's Mocks Aren't Stubs, but still don't understand the difference.

推荐答案

Stub

我认为最大的区别是您已经编写的存根具有预定的行为.因此,您将拥有一个实现依赖项(最有可能是抽象类或接口)的类,您为了测试目的而伪造,并且这些方法将被设置响应剔除.他们不会做任何花哨的事情,而且您已经在测试之外为其编写了存根代码.

I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the dependency (abstract class or interface most likely) you are faking for testing purposes and the methods would just be stubbed out with set responses. They would not do anything fancy and you would have already written the stubbed code for it outside of your test.

模拟

模拟是作为测试的一部分,您必须根据自己的期望进行设置.模拟不是以预先确定的方式设置的,因此您有在测试中执行它的代码.以某种方式模拟是在运行时确定的,因为设置期望的代码必须在它们执行任何操作之前运行.

A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.

Mock 和 Stub 的区别

用模拟编写的测试通常遵循 initialize ->设定期望 ->锻炼 ->验证 模式进行测试.虽然预先编写的存根将遵循 initialize ->锻炼 ->验证.

Tests written with mocks usually follow an initialize -> set expectations -> exercise -> verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify.

模拟和存根之间的相似性

两者的目的都是为了消除对类或函数的所有依赖项的测试,以便您的测试在他们试图证明的内容上更加集中和简单.

The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.

这篇关于模拟 & 和有什么不一样?存根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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