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

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Determine if a Column Exists in a DataReader

Setting Default Values in an Angular Reactive Form