我无法验证 IInterface.SomeMethod<T>(T arg)
的模拟使用 Moq.Mock.Verify
调用.
我可以使用 It.IsAny<IGenericInterface>()
验证该方法是在“标准”接口(interface)上调用的或 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());
}
这是我正在测试的类(class):
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);
}
这是我的接口(interface)/类继承层次结构:
public interface ISpecificCommand
{
}
public class ConcreteSpecificCommand : ISpecificCommand
{
}
最佳答案
这是当前发行版 Moq 4.0.10827 中的一个已知问题。请参阅 GitHub 上的讨论 https://github.com/Moq/moq4/pull/25 .我已经下载了它的开发分支,编译并引用了它,现在你的测试通过了。
关于c# - 验证使用 Moq 调用的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124934/