什么时候使用存根和模拟? [英] When to use stubs and mocks?

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

问题描述

我一直都很困惑.如果我编写的代码使用伪造的代码来声明某些操作,那么当我开始使用真正的对象而不是伪造的对象时,我如何信任我的真正实现.

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.

例如,我有这段代码-

    [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使用术语测试双精度"作为任何种类的假装对象的通用术语,以代替用于测试目的的真实对象.该名称来自电影中的特技双重概念. (他的目的之一是避免使用任何已经被广泛使用的名称.)然后,梅萨罗斯定义了四种特殊的双精度类型:

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:

  • 虚拟对象可以传递,但从未实际使用过.通常它们仅用于填充参数列表.
  • 伪造的对象实际上具有有效的实现,但是通常采取一些捷径,这使它们不适合生产(内存数据库是一个很好的例子).
  • 存根提供对测试期间进行的呼叫的固定答复,通常不响应为测试编程的内容之外的任何内容.存根还可以记录有关呼叫的信息,例如,电子邮件网关存根可以记住已发送"的消息,或者仅记住已发送"的消息数量.
  • 模拟是我们在这里谈论的:具有期望的预编程对象,这些对象构成了期望接收的呼叫的规范.

在这些类型的双打中,只有嘲笑者坚持进行行为验证.

Of these kinds of doubles, only mocks insist upon behavior verification.

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

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