Mocking generic methods in Moq without specifying T

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

    I couldn't find any information on mocking the generic methods with a generic mock method, using Moq. The only thing I found so far was mocking the generic methods per-specific-type, which is not helping, because, in general, you can't really foresee all the possible cases/variations of generic parameters in advance.

    So I resolved this kind of issue by creating my own fake/empty implementation of that interface, instead of using Moq.

    In your case, it would look like this:

    public interface IRepo
    {
        IA Reserve();
    }
    
    public class FakeRepo : IRepo
    {
        public IA Reserve()
        {
            // your logic here
        }
    }
    

    Afterwards, just inject that fake implementation in place of IRepo usage.

提交回复
热议问题