I spent an evening trying to mock an object that implements IQueryable:
public interface IRepo<T> : IQueryable<T>
{
}
The best I could come up with is something like this:
var items = new Item[] {}.AsQueryable();
var repo = new Mock<IRepo>();
repo.Setup(r => r.GetEnumerator()).Returns(items.GetEnumerator());
repo.Setup(r => r.Provider).Returns(items.Provider);
repo.Setup(r => r.ElementType).Returns(items.ElementType);
repo.Setup(r => r.Expression).Returns(items.Expression);
Is there a more concise way to do the same? It would be easier to expose a property/method in IRepo that returns IQueryable and the simply mock like this:
repo.Setup(r => r.GetItems()).Returns(new Items[]{ }.AsQueryable());
But this is not what I want to do =)
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:
Hope that saves someone some time.
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:
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. :)
I think that's about the best you can do with Moq. I think a more readable option would be to roll your own
FakeRepo<T>
that derives fromSystem.Linq.EnumerableQuery<T>
:Update: You might be able to pull this off by mocking
EnumerableQuery<T>
then usingAs<T>()
:I like Rune's answer. Here's a generic IQueryable version:
I had the same issue. I've fixed it by changing this line
to
I hope that additional comments are not required here.