[c#] Mocking Extension Methods with Moq

I have a preexisting Interface...

public interface ISomeInterface
{
    void SomeMethod();
}

and I've extended this intreface using a mixin...

public static class SomeInterfaceExtensions
{
    public static void AnotherMethod(this ISomeInterface someInterface)
    {
        // Implementation here
    }
}

I have a class thats calling this which I want to test...

public class Caller
{
    private readonly ISomeInterface someInterface;

    public Caller(ISomeInterface someInterface)
    {
        this.someInterface = someInterface;
    }

    public void Main()
    {
        someInterface.AnotherMethod();
    }
}

and a test where I'd like to mock the interface and verify the call to the extension method...

    [Test]
    public void Main_BasicCall_CallsAnotherMethod()
    {
        // Arrange
        var someInterfaceMock = new Mock<ISomeInterface>();
        someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable();

        var caller = new Caller(someInterfaceMock.Object);

        // Act
        caller.Main();

        // Assert
        someInterfaceMock.Verify();
    }

Running this test however generates an exception...

System.ArgumentException: Invalid setup on a non-member method:
x => x.AnotherMethod()

My question is, is there a nice way to mock out the mixin call?

This question is related to c# unit-testing mocking extension-methods moq

The answer is


You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach. Here is the description of the tool:

Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.

Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

You can use Moles with any testing framework (it's independent about that).


I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.

I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.


I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.

See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.


I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/


So if you are using Moq, and want to mock the result of an Extension method, then you can use SetupReturnsDefault<ReturnTypeOfExtensionMethod>(new ConcreteInstanceToReturn()) on the instance of the mock class that has the extension method you are trying to mock.

It is not perfect, but for unit testing purposes it works well.


You can easily mock an extension method with JustMock. The API is the same as mocking normal method. Consider the following

public static string Echo(this Foo foo, string strValue) 
{ 
    return strValue; 
}

To arrange and verify this method use the following:

string expected = "World";

var foo = new Foo();
Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);

string result = foo.Echo("Hello");

Assert.AreEqual(expected, result);

Here is also a link to the documentation: Extension Methods Mocking

Disclaimer. I am one of the developers responsible for JustMock.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to unit-testing

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to test the type of a thrown exception in Jest Unit Tests not discovered in Visual Studio 2017 Class Not Found: Empty Test Suite in IntelliJ Angular 2 Unit Tests: Cannot find name 'describe' Enzyme - How to access and set <input> value? Mocking HttpClient in unit tests Example of Mockito's argumentCaptor How to write unit testing for Angular / TypeScript for private methods with Jasmine Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Examples related to mocking

How can I mock the JavaScript window object using Jest? How can I mock an ES6 module import using Jest? Mocking a function to raise an Exception to test an except block Unfinished Stubbing Detected in Mockito Python mock multiple return values How do I mock a service that returns promise in AngularJS Jasmine unit test? How do Mockito matchers work? Mocking static methods with Mockito How to spyOn a value property (rather than a method) with Jasmine How do I mock a class without an interface?

Examples related to extension-methods

The operation cannot be completed because the DbContext has been disposed error Extension methods must be defined in a non-generic static class Java equivalent to C# extension methods Razor HtmlHelper Extensions (or other namespaces for views) Not Found Mocking Extension Methods with Moq AddRange to a Collection Distinct() with lambda? Convert string[] to int[] in one line of code using LINQ How do I extend a class with c# extension methods? Static extension methods

Examples related to moq

Mocking HttpClient in unit tests Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."? How can I tell Moq to return a Task? How to mock static methods in c# using MOQ framework? Moq, SetupGet, Mocking a property Mocking a method to throw an exception (moq), but otherwise act like the mocked object? Verify a method call using Moq Verifying a specific parameter with Moq Mocking Extension Methods with Moq Assigning out/ref parameters in Moq