如何模拟私有字段

如何模拟私有字段

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

问题描述

我对模拟真的很陌生,正在尝试用模拟对象替换私有字段.目前,私有字段的实例是在构造函数中创建的.我的代码看起来像...

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.

提前致谢.

推荐答案

我几乎引用了 "有效使用遗留代码":

  1. 在单元测试中对您的类进行子类化,并用其中的模拟对象取代您的私有变量(通过添加公共设置器或在构造函数中).您可能必须使变量受保护.
  2. 为这个私有变量创建一个受保护的 getter,并在测试子类中覆盖它以返回一个模拟对象而不是实际的私有变量.
  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.

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

08-16 02:54