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 = "bonscott@acdc.com" });
mockContacts.Add(new Contact { Id = 2, Email = "brianjohnson@acdc.com" });
mockContacts.Add(new Contact { Id = 3, Email = "angusyoung@acdc.com" });
mockContacts.Add(new Contact { Id = 4, Email = "malcolmyoung@acdc.com" });
mockContacts.Add(new Contact { Id = 5, Email = "cliffwilliams@acdc.com" });
mockContacts.Add(new Contact { Id = 6, Email = "philrudd@acdc.com" });
 
_userRepoMock.Setup(x => x.Contacts).Returns(mockContacts.AsQueryable());

Comments

Popular posts from this blog

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

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