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

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

问题描述

我刚刚阅读了关于模拟对象的维基百科文章,但我仍然不完全清楚出于他们的目的.当实际对象过于复杂或不可预测时,它们似乎是由测试框架创建的对象(您 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 并返回一个 bool.当我传递 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天全站免登陆