Mocking generic methods in Moq without specifying T

后端 未结 6 746
我在风中等你
我在风中等你 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:18

    Simply do this:

    [TestMethod]
    public void ExampleTest()
    {
      var mock = new Mock { DefaultValue = DefaultValue.Mock, };
      // no setups needed!
    
      ...
    }
    

    Since your mock does not have behavior Strict, it will be happy with calls that you haven't even set up. In that case a "default" is simply returned. Then

    DefaultValue.Mock
    

    ensures that this "default" is a new Mock<> of appropriate type, instead of just a null reference.

    The limitation here is that you cannot control (e.g. make special setups on) the individual "sub-mocks" that are returned.

提交回复
热议问题