Rhino - 模拟类而不覆盖虚拟方法
如果我正在模拟一个类,如下所示,有什么方法可以让模拟不覆盖虚拟方法?我知道我可以简单地删除 virtual 修饰符,但我实际上想稍后删除此方法的行为。
换句话说,除了删除 virtual 修饰符之外,如何才能通过此测试:
namespace Sandbox {
public class classToMock {
public int IntProperty { get; set; }
public virtual void DoIt() {
IntProperty = 1;
}
}
public class Foo {
static void Main(string[] args) {
classToMock c = MockRepository.GenerateMock<classToMock>();
c.DoIt();
Assert.AreEqual(1, c.IntProperty);
Console.WriteLine("Pass");
}
}
}
If I'm mocking a class, like below, is there any way I can get the mock to not override a virtual method? I know I can simply remove the virtual modifier, but I actually want to stub out behavior for this method later.
In other words, how can I get this test to pass, other than removing the virtual modifier:
namespace Sandbox {
public class classToMock {
public int IntProperty { get; set; }
public virtual void DoIt() {
IntProperty = 1;
}
}
public class Foo {
static void Main(string[] args) {
classToMock c = MockRepository.GenerateMock<classToMock>();
c.DoIt();
Assert.AreEqual(1, c.IntProperty);
Console.WriteLine("Pass");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想使用 部分模拟,它只会覆盖创建期望时的方法:
You want to use a partial mock, which will only override the method when you create an expectation:
我在这里看到了一些事情。
首先,您正在嘲笑一个具体的班级。在大多数/所有情况下,这是一个坏主意,通常表明您的设计存在缺陷(恕我直言)。如果可能的话,提取一个接口并模拟它。
其次,尽管从技术上讲,模拟正在重写虚拟方法,但最好考虑一下它实际上正在做的事情是通过提供实现来模拟/伪造该方法(一个在这种情况下什么也不做)。一般来说,当您模拟一个对象时,您需要提供测试用例所需的每个属性或方法的实现。
更新:另外,我认为删除“虚拟”将阻止框架使用该方法执行任何操作。
I see a couple of things here.
First, you are mocking a concrete class. In most/all cases, this is a bad idea, and usually indicates a flaw in your design (IMHO). If possible, extract an interface and mock that.
Second, although technically the mock is overriding the virtual method, it might be better to think of what it is doing is actually mocking/faking the method by providing an implementation (one that does nothing in this case). In general, when you mock an object, you need to provide the implementation for each property or method your test case requires of the object.
Update: also, I think removing "virtual" will prevent the framework from being able to do anything with the method.