我在验证使用Moq.Mock.Verify
调用IInterface.SomeMethod<T>(T arg)
的模拟时遇到问题。验证使用Moq调用的泛型方法
我可以验证的方法被称为“标准”接口或者使用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());
}
这是我下的测试类:
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>(T command);
}
这里是我的接口/类继承层次结构:
public interface ISpecificCommand
{
}
public class ConcreteSpecificCommand : ISpecificCommand
{
}
这已经被纠正。 – arni 2014-10-19 17:12:50