我无法验证该模拟IInterface.SomeMethod<T>(T arg)
被称为使用Moq.Mock.Verify
.
我可以验证该方法是在“标准”接口上调用的It.IsAny<IGenericInterface>()
or 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
{
}