什么是模拟,何时应​​使用? [英] What is a mock and when should you use it?

查看:81
本文介绍了什么是模拟,何时应​​使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了模拟对象上的Wikipedia文章,但我仍然不太清楚出于他们的目的.看来它们是由测试框架创建的对象,当实际对象过于复杂或不可预测时(您知道100%可以确定模拟对象的值是因为完全控制了它们).

I just read the Wikipedia article on mock objects, but I'm still not entirely clear on their purpose. It appears they are objects that are created by a test framework when the actual object would be too complex or unpredictable (you know 100% sure what the values of the mock object are because you fully control them).

但是,我的印象是所有测试都是使用已知值的对象完成的,因此我肯定会丢失一些东西.例如,在一个课程项目中,我们的任务是使用日历应用程序.我们的测试套件由事件对象组成,我们确切地知道它们是什么,因此我们可以测试多个事件对象,各种子系统和用户界面之间的交互.我猜这些都是模拟对象,但是我不知道为什么不这么做,因为如果没有已知值的对象,就无法测试系统.

However, I was under the impression that all testing is done with objects of known values, so I must be missing something. For example, in a course project, we were tasked with a calendar application. Our test suite consisted of event objects that we knew exactly what they were so we could test the interactions between multiple event objects, various subsystems, and the user interface. I'm guessing these are mock objects, but I don't know why you wouldn't do this because without the objects of known values, you can't test a system.

推荐答案

模拟对象不仅仅是具有已知值的对象.它是一个对象,具有与您无法在测试中使用的复杂对象(例如数据库连接和结果集)相同的接口,但是具有可以在测试中控制的实现.

A mock object is not just an object with known values. It is an object that has the same interface as a complex object that you cannot use in test (like a database connection and result sets), but with an implementation that you can control in your test.

有一些模拟框架,可让您即时创建这些对象,并且从本质上讲,您可以这样说:使用带方法foo的对象使我成为一个对象,该方法采用int并返回布尔值.当我传递0时,它应该返回true.然后,您可以测试使用foo()的代码,以确保其做出适当的反应.

There are mocking frameworks that allow you to create these objects on the fly and in essence allow you to say something like: Make me an object with a method foo that takes an int and returns a bool. When I pass 0, it should return true. Then you can test the code that uses foo(), to make sure it reacts appropriately.

马丁·福勒(Martin Fowler)有一篇关于嘲讽的好文章:

Martin Fowler has a great article on mocking:

这篇关于什么是模拟,何时应​​使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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