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
(like DbSet
) then you can create your own Include
extension to IQueryable
. Your code will automaticalyl invoke your new Include extension method. When used on an abstraction that returns a DbQuery
, it'll invoke the correct Invoke, else if it's a IQueryable
instance it'll do nothing. Adding this new extension method means that your current code should compile without any changes.
like such:
/// see: http://msdn.microsoft.com/en-us/library/ff714955.aspx
///
/// The method has been modified from version that appears in the referenced article to support DbContext in EF 4.1 ->
///
/// </summary>
public static class ModelExtensions {
public static IQueryable<T> Include<T>
(this IQueryable<T> sequence, string path) where T : class {
var dbQuery = sequence as DbQuery<T>;
if (dbQuery != null) {
return dbQuery.Include(path);
}
return sequence;
}
}
So if your unit test uses a fake IQueryable
list, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With