模拟、存根和工厂女孩之间有什么区别?
我对 rspec 和整个 TDD 方法还很陌生。有人可以解释一下模拟和存根之间的区别吗?我们什么时候使用它们以及什么时候使用 Factory Girl 在测试用例中创建对象?
I'm pretty new to rspec and the whole TDD methodology. Can someone please explain the difference between mock and stub. When do we use them and when do we use Factory Girl to create objects in test cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一站是 Martin Fowler 的著名文章:模拟不是存根
编辑
Mocks
和Stubs
是 测试替身(Mezaros 术语)。测试替身通常用于模拟被测系统(或被测类)所需的依赖关系,以便 SUT/CUT 可以与其依赖关系隔离地进行测试。 (警告 - 精确的术语可能是一个非常敏感的话题,例如 杰夫在这里)来自维基百科:
示例
*
Mockito (Java) 和 Moq (.Net) 允许您使用最少的代码动态针对依赖项的接口构建模拟类,并提供以下功能验证 SUT 是否正确交互模拟,例如通过检查 SUT 是否使用正确的参数调用模拟的方法正确的次数。* 免责声明 - 我不是 ruby 开发人员
Your first stop is Martin Fowler's famous article : Mocks are not Stubs
Edit
Mocks
andStubs
are two of the types of Test Doubles (Mezaros terminology). Test doubles are typically used to simulate the dependencies needed by a System Under Test (or Class Under Test), so that the SUT / CUT may be tested in isolation from its dependencies. (Caveat - precise terminology can be quite a touchy subject e.g. as mentioned by Jeff here)From wikipedia:
Examples
*
Frameworks like Mockito (Java) and Moq (.Net) allow you to build mock classes against a dependency's interface on the fly with a minimum of code, and provide the ability to verify that the SUT interacted correctly with the mock, e.g. by checking that the SUT invoked the mock's methods the correct number of times, with the correct parameters.* Disclaimer - I'm not a ruby dev
您可以将模拟(或双重)视为假对象。当您进行测试并需要使用在测试中不易使用的对象时,您可以使用模拟作为您期望该对象的行为和工作方式的近似值。存根可以以类似的方式使用,但用于对象的单个方法。
这是一个相当人为地使用两者的示例:
您可以想象使用大量模拟或存根是一个坏主意;这基本上屏蔽了测试中的部分代码,但是对于一些困难/罕见的测试场景来说,这是一个简单的解决方案。
Factory Girl 对于生成测试数据非常有用。您将使用工厂作为为模型创建实例的配方,您可能需要测试涉及大量测试数据的某些内容,这将是使用固定装置不起作用并且显式创建复杂对象可能很乏味的情况。
You could think of a mock (or double) as a fake object. When you're testing and need to work with an object that isn't easily usable inside your test, you could use a mock as an approximation for how you expect that object to behave and work around it. Stubs can be used in a similar manner but on an individual method on an object.
Here's a rather contrived example of using a lot of both:
You can imagine that using a lot of mocks or stubbing is a bad idea; this is basically masking out parts of your code in your test but, it's an easy solution for some difficult/rare testing scenarios.
Factory Girl is useful for generating data for tests. You would use factories as recipes for creating instances for your models, you might need to test something involving a lot of test data and this would be a situation where using fixtures won't work and creating complicated objects explicitly can be tedious.