Setup result for call to extension method

17,410

Solution 1

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.

Solution 2

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.

Solution 3

It is possible, although not pretty... I assume there is some internal cache object inside your extension method, or a reference to some cache somewhere. You can use reflection to replace the internal object to store the cache. You get something like this inside your test:

IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());

Mock<ICache> internalCache = new Mock<ICache>();
internalCache.Setup(i => i.Get<String>("CacheKey")).Returns("Foo");

var cacheExtension = typeof(CacheExtensions);
var inst = cacheExtension.GetField("_internalCache", BindingFlags.NonPublic | BindingFlags.Static);
inst.SetValue(cacheExtension, internalCache.Object);

Note that this code is not tested, but it should explain the basic idea.

Share:
17,410
Jamie Dixon
Author by

Jamie Dixon

Co-founder https://leadpal.io

Updated on June 06, 2022

Comments

  • Jamie Dixon
    Jamie Dixon almost 2 years

    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?

  • Jamie Dixon
    Jamie Dixon almost 12 years
    Thanks @FlorianGreinacher. The only problem with this is that I can't setup Get since it's non-virtual.
  • Jamie Dixon
    Jamie Dixon almost 12 years
    Thanks for your help. I decided to ditch the extension method and impliment my own ICache as sugested. Everything looks much simpler now.