Rhino - Mocking classes and not overriding virtual methods

独自空忆成欢 提交于 2019-12-07 04:45:17

问题


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");
    }
}

}


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/5732611/rhino-mocking-classes-and-not-overriding-virtual-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!