TypeMock:使用伪值模拟类

时间:2011-08-19 11:31:01

标签: typemock

大家好,

我有一个班级“Abc”,其中我有一些只读属性(Context)。在“Abc”类的构造函数中,我使用私有变量(_context)将值设置为只读属性。例如Abc() {_context=new Xyz();}

我想使用TypeMock创建一个测试用例,我想在其中模拟Xyz类并将值返回_context。这样我就可以使用一些假数据来填充上下文。

请告诉我是否有可能用值来模拟课程。感谢

1 个答案:

答案 0 :(得分:3)

您想要了解的是Isolator的“交换”功能。

// First set up your fake Xyz.
var fakeXyz = Isolate.Fake.Instance<Xyz>();
Isolate.WhenCalled(() => fakeXyz.SomeMethod()).WillReturn("Value");

// Now tell Isolator that the next time someone does
// "new Xyz()" you want it to be your fake.
Isolate.Swap.NextInstance<Xyz>().With(fakeXyz);

// Create your Abc and do your assertions. This should pass:
var realAbc = new Abc();
Assert.AreEqual("Value", realAbc.Context.SomeMethod();

找出这种基本隔离器功能的一个很好的参考是the online documentation on the Typemock site。查看“快速入门”和“使用Typemock Isolator”部分。还有更多的例子可以向您展示如何做类似和更高级的事情。

更新:我之前展示了Assert.AreSame(fakeXyz, realAbc.Context)作为验证互换的方式。似乎在某些版本的Typemock中,Assert.AreSame将失败,因为有某种动态代理机制在起作用 - 它们实际上并没有交换为字面上相同的假实例 ,他们正在做一些让事情发生的诡计。但是,仍会调用对假实例的调用,您仍然可以获得预期的结果。我已相应更新了示例代码段。

相关问题