何时使用存根和模拟? [英] When to use stubs and mocks?
问题描述
我一直有这种困惑.如果我编写了一个使用假代码来断言某些操作的代码,当它开始真正使用真实对象而不是假对象时,我如何相信我的真实实现.
I've this confusion all the time. If I write a code which uses fake code to assert some operation, how do i trust my real implementation when it is started really using the real objects instead of fake ones.
例如,我有这个代码--
For example, I've this code --
[Test]
public void CanCreateContactsWithData()
{
using(ISession session = factory.OpenSession())
using (ITransaction trans = session.BeginTransaction())
{
_contactId = (long) session.Save(contact);
trans.Commit();
}
Assert.AreNotEqual(0, _contactId);
}
此代码测试联系人"对象的实现,是否将其保存到数据库中.如果我碰巧使用存根而不是真正的数据库连接,是否需要单独测试将其存储在数据库中?而且,你们称之为集成测试吗?
This code tests the implementation of a "contact" object whether that gets saved into database or not. If i happened to use a stub instead of a real database connection, do I need to have separate test for storing it in database? And, do you guys call that as integration testing?
非常感谢您的回答.
推荐答案
Martin Fowler 有一个很好的讨论 这里.
Martin Fowler has a good discussion here.
来自他的文章:
Meszaros 使用术语 Test Double 作为通用术语,用于代替真实对象用于测试目的的任何类型的假装对象.这个名字来源于电影中特技替身的概念.(他的目标之一是避免使用任何已经被广泛使用的名称.)Meszaros 然后定义了四种特殊类型的双精度:
Meszaros uses the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes. The name comes from the notion of a Stunt Double in movies. (One of his aims was to avoid using any name that was already widely used.) Meszaros then defined four particular kinds of double:
- 虚拟对象被传递,但从未真正使用过.通常它们只是用来填充参数列表.
- 假对象实际上有工作实现,但通常采取一些捷径,使它们不适合生产(内存数据库就是一个很好的例子).
- 存根为测试期间拨打的电话提供预设答案,通常根本不响应任何超出测试程序的内容.存根还可以记录有关呼叫的信息,例如记住它发送"的消息的电子邮件网关存根,或者可能只记录它发送"的消息的数量.
- Mocks 就是我们在此讨论的内容:预先编程了期望的对象,这些期望形成了它们期望接收的调用的规范.
在这些类型的替身中,只有模拟坚持行为验证.
Of these kinds of doubles, only mocks insist upon behavior verification.
这篇关于何时使用存根和模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!