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.
ListmockContacts = 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
Post a Comment