我读过各种关于测试中模仿和存根的文章,包括Martin Fowler的《Mocks Aren't Stubs》,但我仍然不理解其中的区别。
当前回答
Mock只是测试行为,确保调用了特定的方法。 Stub是特定对象的可测试版本(本质上)。
你说的苹果方式是什么意思?
其他回答
Stubs vs. Mocks Stubs provide specific answers to methods calls ex: myStubbedService.getValues() just return a String needed by the code under test used by code under test to isolate it cannot fail test ex: myStubbedService.getValues() just returns the stubbed value often implement abstract methods Mocks "superset" of stubs; can assert that certain methods are called ex: verify that myMockedService.getValues() is called only once used to test behaviour of code under test can fail test ex: verify that myMockedService.getValues() was called once; verification fails, because myMockedService.getValues() was not called by my tested code often mocks interfaces
他使用的通用术语是测试替身(想想特技替身)。Test Double是一个通用术语,用于为测试目的替换生产对象的任何情况。杰拉德列出了各种各样的替身:
Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists. Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example). Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent(also called Partial Mock). Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
源
存根是为测试目的而构建的伪对象。mock是记录预期调用是否有效发生的存根。
Stub
存根是用来伪造具有预先编程行为的方法的对象。为了避免不必要的副作用(例如,存根可能会进行一个虚假的获取调用,返回预先编程的响应,而不实际向服务器发出请求),您可能会使用这个方法来代替现有的方法。
Mock
mock是用来模拟具有预编程行为和预编程期望的方法的对象。如果这些期望没有得到满足,那么mock将导致测试失败(例如,mock可以进行一个虚假的获取调用,返回预先编程的响应,而不实际向服务器发出请求,例如,第一个参数是“http://localhost:3008/”,否则测试将失败。)
区别
与模拟不同,存根没有预先编程的可能导致测试失败的期望。
存根是一个空函数,用于在测试期间避免未处理的异常:
function foo(){}
mock是一个人为的函数,用于避免在测试期间对操作系统、环境或硬件的依赖:
function foo(bar){ window = this; return window.toString(bar); }
在断言和状态方面:
在事件或状态更改之前断言模拟 存根不被断言,它们在事件之前提供状态,以避免执行来自不相关单元的代码 间谍就像存根一样被设置,然后在事件或状态改变后被断言 假的是不断言的,他们运行后的事件硬编码的依赖,以避免状态
参考文献
极客词汇:Mock 极客词汇:存根 极客术语:间谍 测试替身:假的,模拟和存根
推荐文章
- 如何使用“测试”包打印Go测试?
- 如何在IntelliJ中为整个项目配置“缩短命令行”方法
- toBe(true) vs toBeTruthy() vs toBeTrue()
- 使用Mockito测试抽象类
- 什么时候应该使用Debug.Assert()?
- 使用Moq模拟扩展方法
- 从控制台停止一个Android应用程序
- 基于输入参数模拟python函数
- 使Android模拟器运行得更快
- 如何“去测试”我的项目中的所有测试?
- 断言对模拟方法的连续调用
- 测试HTML电子邮件渲染
- 测试过程。环境与玩笑
- Rspec:“数组。应该== another_array"而不考虑顺序
- 如何检查字符串数组是否包含JavaScript字符串?