is it possible to mock/fake an extension method?

左心房为你撑大大i 提交于 2019-12-17 20:58:13

问题


I'm using a controller extension, and I tried to mock it using FakeItEasy (v 1.7.4) like this:

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)

回答1:


This is not possible. Proxying/intercepting libraries used by FakeItEasy (and other popular free frameworks, like Moq or RhinoMocks) don't allow interception of static methods (static properties, sealed classes and non-virtual instance methods in fact). And extension method is just a kind of static method.

You can take a look at TypeMock or JustMock, which do have such functionality.




回答2:


If the extension method is declared in a separate assembly, you could link in a replacement assembly with the same namespace.

You'd have to replace any other required types from this assembly too, though.




回答3:


In FakeItEasy you can create it as a strict mock and then configure the static method

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



来源:https://stackoverflow.com/questions/9064566/is-it-possible-to-mock-fake-an-extension-method

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