我如何模拟私人领域? [英] How do I mock a private field?

查看:220
本文介绍了我如何模拟私人领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是真正的新嘲笑,我试图用一个模拟对象来代替私有字段。目前,私人领域的实例在构造函数中被创建。我的代码看起来像...

I'm really new to mocks and am trying to replace a private field with a mock object. Currently the instance of the private field is created in the constructor. My code looks like...

public class Cache {
    private ISnapshot _lastest_snapshot;

    public ISnapshot LatestSnapshot {
        get { return this._lastest_snapshot; }
        private set { this._latest_snapshot = value; }
    }

    public Cache() {
        this.LatestSnapshot = new Snapshot();
    }

    public void Freeze(IUpdates Updates) {
        ISnapshot _next = this.LastestSnapshot.CreateNext();
        _next.FreezeFrom(Updates);
        this.LastestSnapshot = _next;
    }

}



我想要做的在创建单元测试断言 ISnapshot.FreezeFrom(IUpdates)从所谓的在 Cache.Freeze(IUpdates)。我猜我应该模仿对象替换私有字段 _latest_snapshot (也许是错误的假设?)。我怎么会去,虽然仍保留一个无参数的构造函数,而不是诉诸让 LatestSnapshot 的集公开?

What I'm trying to do is create a unit test that asserts ISnapshot.FreezeFrom(IUpdates) is called from within Cache.Freeze(IUpdates). I'm guessing I should replace the private field _latest_snapshot with a mock object (maybe wrong assumption?). How would I go about that while still retaining a parameterless constructor and not resorting to making LatestSnapshot's set public?

如果我完全准备有关编写测试走错了路,然后请你指出为好。

If I'm totally going about writing the test the wrong way then please do point out as well.

在实际执行 ISnapshot.FreezeFrom的本身的调用了深刻的对象图其他方法层次结构,所以我不是太热衷于断言对象图。

The actual implementation of ISnapshot.FreezeFrom itself calls a heirarchy of other methods with a deep object graph so I'm not too keen on asserting the object graph.

在此先感谢

推荐答案

我几乎援引的修改代码有效地开展工作:

I'm almost citing techniques from "Working Effectively with Legacy Code":


  1. 子类的一个单元测试类,并取代用它模拟对象的私有变量(通过添加一个公共setter方法或构造函数)。你很可能得把这些变量的保护。

  2. 请为这个私有变量受保护的吸气剂,并覆盖它在测试中的子类返回模仿对象,而不是实际的私有变量的。

  3. 创建创建一个受保护的工厂方法 ISnapshot 对象,并重写它在测试中的子类返回模仿对象,而不是真正的实例。这样的构造会从一开始就正确的价值。

  4. 参数多态构造带的一个实例 ISnapshot

  1. Sub-class your class in a unit test and supersede your private variable with a mock object in it (by adding a public setter or in the constructor). You probably have to make the variable protected.
  2. Make a protected getter for this private variable, and override it in testing subclass to return a mock object instead of the actual private variable.
  3. Create a protected factory method for creating ISnapshot object, and override it in testing subclass to return an instance of a mock object instead of the real one. This way the constructor will get the right value from the start.
  4. Parametrize constructor to take an instance of ISnapshot.

这篇关于我如何模拟私人领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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