Testing a General Method Called Using Moq

I'm having trouble verifying that the IInterface.SomeMethod<T>(T arg) layout is IInterface.SomeMethod<T>(T arg) called using Moq.Mock.Verify .

I can check if this method is called on the "standard" interface either with It.IsAny<IGenericInterface>() or It.IsAny<ConcreteImplementationOfIGenericInterface>() , and I have no problem checking the general method call with It.IsAny<ConcreteImplementationOfIGenericInterface>() , but I can’t check the general method was called using It.IsAny<IGenericInterface>() - it always says that the method was not called, and the unit test fails.

Here is my unit test:

 public void TestMethod1() { var mockInterface = new Mock<IServiceInterface>(); var classUnderTest = new ClassUnderTest(mockInterface.Object); classUnderTest.Run(); // next three lines are fine and pass the unit tests mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once()); mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ISpecificCommand>()), Times.Once()); mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once()); // this line breaks: "Expected invocation on the mock once, but was 0 times" mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ISpecificCommand>()), Times.Once()); } 

Here is my test:

 public class ClassUnderTest { private IServiceInterface _service; public ClassUnderTest(IServiceInterface service) { _service = service; } public void Run() { var command = new ConcreteSpecificCommand(); _service.GenericMethod(command); _service.NotGenericMethod(command); } } 

Here is my IServiceInterface :

 public interface IServiceInterface { void NotGenericMethod(ISpecificCommand command); void GenericMethod<T>(T command); } 

And here is my interface / class inheritance hierarchy:

 public interface ISpecificCommand { } public class ConcreteSpecificCommand : ISpecificCommand { } 
+8
c # moq
source share
2 answers

This is a known issue in Moq 4.0.10827, which is the current version. See this discussion on GitHub https://github.com/Moq/moq4/pull/25 . I downloaded its dev branch, compiled and referenced it, and now your test passes.

+6
source share

I am going to do it. Since GenericMethod<T> requires the T argument to be provided, one could do:

 mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.Is<object>(x=> typeof(ISpecificCommand).IsAssignableFrom(x.GetType()))), Times.Once()); 
0
source share

All Articles