views:

307

answers:

2

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?

A: 

I think it is not possible to mock extension methods. They are effectively static methods with a bit of syntactic sugar on top, and you can't mock these. Yet another reason to avoid using extension methods :)

Grzenio
@-1er: Why not share your insight along with your ire and issue a comment to go with your -1? Or perhaps wrap it in a constructive answer like Mark's?
Ruben Bartelink
+2  A: 

You may want to read (Moq co-author) Daniel Cazzulino's blog post How to mock extension methods.

However, personally, I don't find this 'nice' in any way...

Mark Seemann