Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Include method of DbSet?

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 ?

like image 332
ashutosh raina Avatar asked Oct 22 '22 19:10

ashutosh raina


1 Answers

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.

like image 193
Quinton Bernhardt Avatar answered Oct 24 '22 17:10

Quinton Bernhardt