Mocking generic methods in Moq without specifying T

后端 未结 6 749
我在风中等你
我在风中等你 2020-12-03 00:45

I have an interface with a method as follows:

public interface IRepo
{
    IA Reserve();
}

I would like to mock the clas

6条回答
  •  死守一世寂寞
    2020-12-03 01:01

    In Moq 4.13 they introduced the It.IsAnyType type which you can using to mock generic methods. E.g.

    public interface IFoo
    {
        bool M1();
        bool M2(T arg);
    }
    
    var mock = new Mock();
    // matches any type argument:
    mock.Setup(m => m.M1()).Returns(true);
    
    // matches only type arguments that are subtypes of / implement T:
    mock.Setup(m => m.M1>()).Returns(true);
    
    // use of type matchers is allowed in the argument list:
    mock.Setup(m => m.M2(It.IsAny())).Returns(true);
    mock.Setup(m => m.M2(It.IsAny>())).Returns(true);
    

提交回复
热议问题