[英]Verifying generic method called using Moq
我無法驗證使用Moq.Mock.Verify
調用IInterface.SomeMethod<T>(T arg)
Moq.Mock.Verify
。
我可以使用It.IsAny<IGenericInterface>()
或It.IsAny<ConcreteImplementationOfIGenericInterface>()
驗證是否在“標准”接口上調用了該方法,並且我沒有使用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
{
}
這是Moq 4.0.10827中的已知問題,它是當前版本。 請參閱GitHub上的討論https://github.com/Moq/moq4/pull/25 。 我已經下載了它的dev分支,編譯並引用它,現在你的測試通過了。
我要發誓。 由於GenericMethod<T>
要求提供T參數,是否可以這樣做:
mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.Is<object>(x=> typeof(ISpecificCommand).IsAssignableFrom(x.GetType()))), Times.Once());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.