Mocking Static Methods Using Rhino.Mocks

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

+46
c # tdd mocking rhino-mocks
Feb 12 '09 at 6:07
source share
6 answers

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

No, It is Immpossible.

TypeMock can do this because it uses the CLR profiler to intercept and divert calls.

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

+70
May 04 '09 at 2:30 p.m.
source share

Wrap the static method call in the virtual instance method in another class, and then say it.

+21
Feb 12 '09 at 6:10
source share

If you cannot use TypeMock to intercept a method call, it is recommended that you use a template to create a proxy server that redirects to non-virtual or static methods that interest you during testing, and then set the expected value for the proxy server. 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 ITypeToTest instead of where you went or installed an instance of TypeToTest , making sure that the default implementation uses TypeToTestProxy as it moves toward the actual implementation. Then you can create the ITypeToTest layout in the test code and set the expectations accordingly.

Please note that creating these proxies can be very tedious, error prone and time consuming. For this, I maintain a library and a set of tools that generate assemblies for you that contain these types. See this page for more details.

+15
Dec 24 '09 at 21:14
source share

The only mockup framework that I know of supports legacy statics - TypeMock.

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

+4
Feb 12 '09 at 22:42
source share

This is the biggest drawback of Rhino Mocks. I do not know that Rhino Mocks is even possible to realize this without rethinking how he does his mockery.

+4
Nov 05 '09 at 3:59
source share

I mocked moq, I don’t think we can mock static members using this because moQ creates a new proxy for the target (class or interface). Thus, only inherited members (virtual in the case of a class, public in terms of interface) can be mocked. It is clear that static members are not inherited, so the problem.

+2
Aug 21 '09 at 10:37
source share



All Articles