我无法验证模拟IInterface.SomeMethod<T>(T arg)被称为使用Moq.Mock.Verify.
我可以验证方法是在"标准"接口上调用使用It.IsAny<IGenericInterface>()或It.IsAny<ConcreteImplementationOfIGenericInterface>(),并且我没有麻烦验证使用泛型方法调用It.IsAny<ConcreteImplementationOfIGenericInterface>(),但我无法验证使用泛型方法调用It.IsAny<IGenericInterface>()- 它总是说该方法没有被调用,单元测试失败.
这是我的单元测试:
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());
}
Run Code Online (Sandbox Code Playgroud)
这是我的课程:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的IServiceInterface:
public interface IServiceInterface
{
void NotGenericMethod(ISpecificCommand command);
void GenericMethod<T>(T command);
}
Run Code Online (Sandbox Code Playgroud)
这是我的接口/类继承层次结构:
public interface ISpecificCommand
{
}
public class ConcreteSpecificCommand : ISpecificCommand
{
}
Run Code Online (Sandbox Code Playgroud)
这是Moq 4.0.10827中的已知问题,它是当前版本.请参阅GitHub上的讨论https://github.com/Moq/moq4/pull/25.我已经下载了它的dev分支,编译并引用它,现在你的测试通过了.