Mocking an IQueryable Return Value‏

When following the Repository pattern it’s often a good idea to return an IQueryable representing the data you wish to expose. But how can you mock this data when writing your unit tests? The AsQueryable() method provides a way. 
In the example below, I create a short list of mock data to be returned from my mock repository. I then setup my mock repository to return that list as an IQueryable using the AsQueryable() method.
List mockContacts = new List(6);
mockContacts.Add(new Contact { Id = 1, Email = "" });
mockContacts.Add(new Contact { Id = 2, Email = "" });
mockContacts.Add(new Contact { Id = 3, Email = "" });
mockContacts.Add(new Contact { Id = 4, Email = "" });
mockContacts.Add(new Contact { Id = 5, Email = "" });
mockContacts.Add(new Contact { Id = 6, Email = "" });
_userRepoMock.Setup(x => x.Contacts).Returns(mockContacts.AsQueryable());


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

Unit Testing with a Mock Entity Framework DbContext and Fake DbSets

A Red Herring When Using Moq to Mock Methods With Optional Parameters