I have the following method in my repository
public IQueryable<T> QueryWithInclude(String include)
{
return _dbSet.Include(include);
}
How can I mock such a method I am using Moq. I can’t seem to find out the correct way.
For e.g. I could do the following for
public IQueryable<T> Query()
{
return _dbSet;
}
mockrepository.Setup(_ => _.Query()).Returns(foo.AsQueryable());
Also, if the mocking of such a method/s eventually turns out be difficult then is it wise to consider alternative implementations/ workarounds ?
As long as your abstractions return
IQueryable(likeDbSet) then you can create your ownIncludeextension toIQueryable. Your code will automaticalyl invoke your new Include extension method. When used on an abstraction that returns aDbQuery, it’ll invoke the correct Invoke, else if it’s aIQueryableinstance it’ll do nothing. Adding this new extension method means that your current code should compile without any changes.like such:
So if your unit test uses a fake
IQueryablelist, the Include will do nothing.I must add though that there are strong opinions on why it is bad and worthless to mock out EntityFramework. If you haven’t see them it may be worth it checking them out.