How to instantiate IQueryable() in C#

Viewed 30

You are writing unit tests and you want to insatiate an IQueryable() interface. How exactly?

2 Answers

One straight forward way would be creating object implementing interface, or to use AsQueryable() method on IEnumerable, as suggested in other answer.

One more way, as generally is done with interfaces, is to use mocks, like

var queryableMock = new Mock<IQueryable>();
// Setup mock with queryableMock.Setup method,
// now you can use queryableMock.Object

To instantiate an empty object use the following code where T is your entity type

using System.Linq;

var query = Enumerable.Empty<T>().AsQueryable();

To instantiate an object with a list of entries:

var query = (new List<T> { new T()}).AsQueryable();
Related