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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With