2013-02-27 67 views
8

我在验证使用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 
{ 
} 

回答

6

它是起订量4.0.10827这是当前发行版的已知问题。请参阅GitHub https://github.com/Moq/moq4/pull/25上的讨论。我已经下载了它的开发分支,编译并引用它,现在你的测试通过了。

+0

这已经被纠正。 – arni 2014-10-19 17:12:50

0

我要继续它。由于GenericMethod<T>需要一件T参数提供,将有可能做到:

mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.Is<object>(x=> typeof(ISpecificCommand).IsAssignableFrom(x.GetType()))), Times.Once()); 
+0

感谢您的意见,但这似乎并不奏效。 – sennett 2013-02-28 20:53:30