Mocking classes that implement IQueryable with Moq

后端 未结 5 1118
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 08:41

I spent an evening trying to mock an object that implements IQueryable:

public interface IRepo : IQueryable
{
}

The best

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 09:31

    This is nothing new, just a cleaner way of doing it. I also have repositories where the repository itself is also an IQueryable, so I needed the same thing. I basically just put your code into an extension method like this at the root level of my test project, to make it available to all tests:

    public static class MockExtensions
    {
        public static void SetupIQueryable(this Mock mock, IQueryable queryable)
            where T: class, IQueryable
        {
            mock.Setup(r => r.GetEnumerator()).Returns(queryable.GetEnumerator());
            mock.Setup(r => r.Provider).Returns(queryable.Provider);
            mock.Setup(r => r.ElementType).Returns(queryable.ElementType);
            mock.Setup(r => r.Expression).Returns(queryable.Expression);
        }
    }
    

    This basically just offers reusability, since you're likely to want to do this in several tests, and in each test it makes the intention clear and the mess minimal. :)

提交回复
热议问题