Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 which would let me accomplish the same?

like image 794
abhilash Avatar asked Feb 12 '09 06:02

abhilash


People also ask

How do you mock static methods in Rhino Mocks?

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.

Can static methods be mocked?

Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

Why should we not mock static methods?

If you need to mock a static method, it is a strong indicator for a bad design. Usually, you mock the dependency of your class-under-test. If your class-under-test refers to a static method - like java.

How do you mock a static property?

As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members. Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.


2 Answers

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.

like image 118
Judah Gabriel Himango Avatar answered Sep 28 '22 03:09

Judah Gabriel Himango


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

like image 44
Rytmis Avatar answered Sep 28 '22 05:09

Rytmis