Mocking classes that implement IQueryable with Moq

后端 未结 5 1121
隐瞒了意图╮
隐瞒了意图╮ 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:20

    Rune's answer is awesome and saved me time figuring out how to do the same. Small gotcha is that if you call some IQueryable extension methods on your IQueryable twice (e.g. ToList()) then the second time you'll get no results back. That's because the enumerator is at the end and needs resetting. Using Rhinomocks I changed the implementation for GetEnumerator to:

    mock.Stub(r => r.GetEnumerator()).Do((Func>) (() => { 
        var enumerator = queryable.GetEnumerator();
        enumerator.Reset();
        return enumerator;
    }));
    

    Hope that saves someone some time.

提交回复
热议问题