C# – Setup result for call to extension method

cmoqnunitunit testing

I'm trying to Setup the return of a call to an extension method and am receiving:

SetUp : System.NotSupportedException : Expression references a method that does not belong to the mocked object: m => m.Cache.GetOrStore<String>("CacheKey", () => "Foo", 900)

It seems to have a problem with referencing the GetOrStore method on the Cache object which is an extension method.

The code compiles but the test fails with this exception.

What do I need to do to setup the result of an extension method like this?

Best Answer

Extension methods can not be mocked like instance methods because they are not defined on your mocked type. They are defined in other static classes. Since you can't simply mock those, you should mock all methods/properties used by the extension method.

This is an example of how extension methods tightly couples your code to other classes. Whatever you do, your class depends on those static methods. You can't mock it and test it in isolation. I suggest refactoring your code to move those methods to their classes of their own if there is any logic inside.

Related Topic