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");
}
}
}
You want to use a partial mock, which will only override the method when you create an expectation:
classToMock c = MockRepository.GeneratePartialMock<classToMock>();
c.DoIt();
Assert.AreEqual(1, c.IntProperty);
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.
精彩评论