validation使用Moq调用的generics方法

我无法validation使用Moq.Mock.Verify调用IInterface.SomeMethod(T arg) Moq.Mock.Verify

我可以使用It.IsAny()It.IsAny()validation是否在“标准”接口上调用了该方法,并且我没有使用It.IsAny()validationgenerics方法调用的It.IsAny() ,但我无法validation使用It.IsAny()调用generics方法 – 它总是说没有调用该方法并且unit testing失败。

这是我的unit testing:

 public void TestMethod1() { var mockInterface = new Mock(); 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()), Times.Once()); mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny()), Times.Once()); mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny()), Times.Once()); // this line breaks: "Expected invocation on the mock once, but was 0 times" mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny()), Times.Once()); } 

这是我的课程:

 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); } } 

这是我的IServiceInterface

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

这是我的接口/类inheritance层次结构:

 public interface ISpecificCommand { } public class ConcreteSpecificCommand : ISpecificCommand { } 

这是Moq 4.0.10827中的一个已知问题,它是当前版本。 请参阅GitHub上的讨论https://github.com/Moq/moq4/pull/25 。 我已经下载了它的dev分支,编译并引用它,现在你的测试通过了。

我要发誓。 由于GenericMethod要求提供T参数,是否可以这样做:

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