Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Russell Giddings Avatar asked Feb 19 '10 11:02

Russell Giddings


People also ask

What can be mocked with Moq?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.

Can you mock a class with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

What is Moq mocking framework?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.


1 Answers

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.

like image 183
Alvis Avatar answered Sep 30 '22 09:09

Alvis