简体   繁体   English

如何模拟包含DbSet的方法?

[英]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. 我怎么能模仿我使用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 . 只要你的抽象返回IQueryable (如DbSet ),那么你可以创建自己的Include扩展IQueryable Your code will automaticalyl invoke your new Include extension method. 您的代码将自动调用您的新Include扩展方法。 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. 当在一个返回DbQuery的抽象上使用时,它将调用正确的Invoke,否则如果它是一个IQueryable实例,它将什么也不做。 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. 因此,如果您的单元测试使用假的IQueryable列表,则Include将不执行任何操作。

I must add though that there are strong opinions on why it is bad and worthless to mock out EntityFramework. 我必须补充说,对于为什么它很糟糕而且毫无价值来嘲笑EntityFramework有强烈的意见。 If you haven't see them it may be worth it checking them out. 如果您还没有看到它们,那么检查它们可能是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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