简体   繁体   中英

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM