Is it possible to mock / fake an extension method?

I am using a controller extension and I tried to mock it with FakeItEasy (v 1.7.4) as follows:

A.CallTo(() => controller.RenderView(A<string>.Ignored,A<object>.Ignored,null)).Returns(""); 

but I get this error:

 System.NullReferenceException : Object reference not set to an instance of an object. at System.Object.GetType() at FakeItEasy.Creation.ProxyGeneratorSelector.MethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget, ref String failReason) at FakeItEasy.Configuration.DefaultInterceptionAsserter.AssertThatMethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget) at FakeItEasy.Configuration.FakeConfigurationManager.CallTo(Expression`1 callSpecification) 
+7
source share
3 answers

It's impossible. Proxying / intercepting libraries used by FakeItEasy (and other popular free frameworks such as Moq or RhinoMocks) do not allow intercepting static methods (static properties, private classes, and non-virtual instance methods in fact). And the extension method is just a kind of static method.

You can look at TypeMock or JustMock , which have this functionality.

+15
source

If the extension method is declared in a separate assembly, you can associate it with a replacement assembly with the same namespace.

You will also have to replace any other required types on this assembly.

+3
source

In FakeItEasy you can create it as a strict layout and then set up a static method

http://hocke.blogspot.com.ar/2011/03/extension-method-for-creating-strict.html

-one
source

All Articles