Mocking Static methods using Rhino.Mocks

2020-01-26 08:31发布

Is it possible to mock a static method using Rhino.Mocks? If Rhino does not support this, is there a pattern or something which would let me accomplish the same?

6条回答
贪生不怕死
2楼-- · 2020-01-26 08:46

The only mock framework that I know of that supports mocking statics is TypeMock.

As Rytmis suggested, you need to wrap the statics in something (i.e. an instance class with virtual methods or an interface) that you can then mock out.

查看更多
够拽才男人
3楼-- · 2020-01-26 08:47

If you can't use TypeMock to intercept the method call, the recommended pattern to use is to create a proxy that forwards to the non-virtual or static methods you are interested in testing, then set the expectation on the proxy. To illustrate, consider the following classes.

class TypeToTest
{
    public void Method() { }
}

interface ITypeToTest
{
    void Method();
}

class TypeToTestProxy : ITypeToTest
{
    TypeToTest m_type = new TypeToTest();

    public void Method() { m_type.Method(); }
}

By creating this proxy, you can now use an ITypeToTest in place of where you were passing or setting a TypeToTest instance, making sure that the default implementation uses the TypeToTestProxy as it forwards to the real implementation. Then, you can create a mock ITypeToTest in your test code and set expectations accordingly.

Note that creating these proxies can be very tedious, error-prone, and time consuming. To address this I maintain a library and set of tools that generate assemblies containing these types for you. Please refer to this page for more information.

查看更多
Ridiculous、
4楼-- · 2020-01-26 08:48

Is it possible to mock a static method using Rhino.Mocks

No, it is not possible.

TypeMock can do this because it utilizes the CLR profiler to intercept and redirect calls.

RhinoMocks, NMock, and Moq cannot do this because these libraries are simpler; they don't use the CLR profiler APIs. They are simpler in that they use proxies to intercept virtual members and interface calls. The downside of this simplicity is that they cannot mock certain things, such as static methods, static properties, sealed classes, or non-virtual instance methods.

查看更多
混吃等死
5楼-- · 2020-01-26 08:51

Wrap the static method call in a virtual instance method in another class, then mock that out.

查看更多
Bombasti
6楼-- · 2020-01-26 08:55

This is the biggest drawback to Rhino Mocks. I don't know that it is even possible for Rhino Mocks to have this implemented without a re-concept of how it does its mocking.

查看更多
我命由我不由天
7楼-- · 2020-01-26 08:55

I have been mocking using moq, I don't think we can mock static members using this because moQ creates a new proxy for the target (class or interface). So only the inheritable members (virtual in case of class, public in terms of interface ) can be mocked. Clearly, static members are not inherited, hence the problem.

查看更多
登录 后发表回答