Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup result for call to extension method

Tags:

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?

like image 792
Jamie Dixon Avatar asked May 23 '12 08:05

Jamie Dixon


People also ask

How do you call an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

How extension method is achieved?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Where do you put extension methods?

An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.


2 Answers

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.

like image 114
Ufuk Hacıoğulları Avatar answered Oct 04 '22 04:10

Ufuk Hacıoğulları


Moq cannot mock static methods, therefore you won't be able to mock your GetOrStore extension.

Instead just mock the Get and Insert methods of the Cache object.

like image 28
Florian Greinacher Avatar answered Oct 04 '22 02:10

Florian Greinacher