2013-02-27 36 views
8

Tôi đang gặp sự cố khi xác minh mẫu giả IInterface.SomeMethod<T>(T arg) được gọi là sử dụng Moq.Mock.Verify.Xác minh phương pháp chung được gọi là sử dụng Moq

Tôi có thể xác minh phương thức được gọi trên giao diện "Chuẩn" hoặc sử dụng It.IsAny<IGenericInterface>() hoặc It.IsAny<ConcreteImplementationOfIGenericInterface>() và tôi không gặp khó khăn khi xác minh cuộc gọi phương thức chung sử dụng It.IsAny<ConcreteImplementationOfIGenericInterface>(), nhưng tôi không thể xác minh phương thức chung được gọi It.IsAny<IGenericInterface>() - nó luôn luôn nói rằng phương pháp này không được gọi và kiểm tra đơn vị không thành công.

Dưới đây là bài kiểm tra đơn vị của tôi:

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()); 
} 

Đây là lớp học của tôi được kiểm tra:

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); 
    } 
} 

Đây là tôi IServiceInterface:

public interface IServiceInterface 
{ 
    void NotGenericMethod(ISpecificCommand command); 
    void GenericMethod<T>(T command); 
} 

Và đây là giao diện của tôi/lớp phân cấp thừa kế:

public interface ISpecificCommand 
{ 
} 

public class ConcreteSpecificCommand : ISpecificCommand 
{ 
} 

Trả lời

6

Đó là một vấn đề được biết đến trong Moq 4.0.10827 mà là một phiên bản phát hành hiện tại. Xem phần thảo luận này tại GitHub https://github.com/Moq/moq4/pull/25. Tôi đã tải về chi nhánh dev của nó, biên soạn và tham chiếu nó và bây giờ thử nghiệm của bạn vượt qua.

+0

Điều này đã được sửa chữa. – arni

0

Tôi sắp sửa cánh. Kể từ GenericMethod<T> đòi hỏi một đối số T được cung cấp, nó sẽ có thể làm:

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

Cảm ơn bạn đã nhập, nhưng điều này dường như không hoạt động. – sennett

Các vấn đề liên quan