我对模拟真的很陌生,正在尝试用模拟对象替换私有字段.目前,私有字段的实例是在构造函数中创建的.我的代码看起来像...
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.
提前致谢.
我几乎引用了 "有效使用遗留代码":
ISnapshot
对象创建一个受保护的工厂方法,并在测试子类中重写它以返回一个模拟对象的实例而不是真实的对象.这样,构造函数将从一开始就获得正确的值.ISnapshot
的实例.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.ISnapshot
.这篇关于如何模拟私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!