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

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

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

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4