質問

This post requires the base class methods to be virtual: question link.

This does not work for me because the base class methods are not virtual (I did not write it and do not have source).

How do I mock out and verify the base class method was called if they are not virtual?

Last criteria - I am developing using Xamarin Studio on Mac. Moq works fine but other frameworks like TypeMock or JustMock (windows install programs) will not work.

役に立ちましたか?

解決

It is not possible. Because of the way Moq works, there is no chance Moq can mock a non-virtual method.

Are you mocking the class type YourClass directly, where YourClass derives from BaseClass, and BaseClass has this (public?) non-virtual non-static method that interests you? So your mock has type Mock<YourClass>, not Mock<IYourClass> where IYourClass is an interface?

Is it strictly necessary that you use BaseClass as a base class, rather than "composing" (having a field of type BaseClass insider your class)?

他のヒント

As mentioned above, Moq can only mock virtual methods.
One possible end run is to wrap your un-moqable class in a proxy and use this proxy in your code.

public class MyUnMoqableClass {
    public string GetValue() {
        return "Hello World";
    }
}

public interface IMyUnMoqableClassProxy {
    string GetValue();
}

public class UnMoqableClassProxy : IMyUnMoqableClassProxy {

    private readonly MyUnMoqableClass _myUnMoqableClass;

    public UnMoqableClassProxy(MyUnMoqableClass myUnMoqableClass) {
        _myUnMoqableClass = myUnMoqableClass;
    }

    public string GetValue() {
        return _myUnMoqableClass.GetValue();
    }

}

It can be a bit (a lot) tedious if you have a large interface on the unmoqable class but does let one isolate the client code.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top