How to mock extension methods with Rhino Mock?

徘徊边缘 提交于 2019-11-28 07:40:08

问题


I have extended objects of type IDataReader with some extension methods that I needed. The problem is now when I try to mock the IDataReader, the extended method is not included in the mock so when the row Expect.Call(reader.ExtensionMethod()).Return(someValue) is reach the ExtensionMethod is executed which is not what I want! I want that call to be record and when the extension method is call from somewhere else I want it to return someValue.

Does anyone know how to get around this?


回答1:


Disclosure: I work for Telerik.

Extension methods are in fact static methods concealed as instance methods. RhinoMock cannot mock static methods and there's no way you can do it, unless you use another mocking library, which uses a profiler.

Such a library is JustMock by Telerik.




回答2:


The answer seems to be no at the moment. To bad though, but I solved my problem with writing a mock class for my interface I wanted to mock instead. Since I didn't needed that many methods of the interface it went pretty fast.




回答3:


It is possible to stub extension method or any other static method without any framework. The following code allows you to do so, you just need to stub _doSumm.

public static class MyExtensions
{
    public static Func<int,int, int> _doSumm = (x, y) => x + y;

    public static int Summ(this int x, int y)
    {
        return _doSumm(x, y);
    }
}



回答4:


In my own instance, I wrapped the extension methods I had to stub into methods of a helper class that exposed the wrapper methods in a new interface. I switched my production code to have an instance of this helper class injected and changed the code to call the new methods. The unit tests are injecting a conveniently crafted stub of the helper interface.

While this solution is not perfect, it is still less dramatic than swapping the mocking framework.



来源:https://stackoverflow.com/questions/3988243/how-to-mock-extension-methods-with-rhino-mock

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