2013-02-27 68 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