【问题标题】:How to create ObjectQuery for testing EF4 'Include' method如何创建 ObjectQuery 以测试 EF4“包含”方法
【发布时间】:2011-10-29 20:26:21
【问题描述】:

我们正在使用 EF4 并为 DAL 层创建测试用例(DAL 层有 linq 查询)。我们使用 TypeMock 作为模拟框架。为了测试,我们正在创建ObjectContext 的Fakecontext 并模拟CreateObjectSet 方法,如下所示:

Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable()); 

以上工作正常。问题是当我们尝试使用“包含”包含相关表时。我们对 include 方法进行了如下扩展:

public static IQueryable<T> Include<T>(this IQueryable<T> source, Expression<Func<T>> property)
{ 
    var objectQuery = source as ObjectQuery<T>; 

    if (objectQuery != null) 
    { 
        var propertyPath = GetPropertyPath(property); 
        return objectQuery.Include(propertyPath); 
    } 

    return source; 
}

所以发生的情况是,在上面的Include 方法中,源类型应该是ObjectQuery&lt;T&gt;。但正如我们已经模拟了CreateObjectSetInclude 方法中的源类型是Collection.Generic.List 类型。请让我们知道在上述情况下我们应该如何模拟。您的及时帮助将不胜感激。谢谢

【问题讨论】:

标签: entity-framework-4 typemock-isolator


【解决方案1】:

Object Services 在编写单元测试时可能很难使用。不幸的是,正如您所发现的那样,没有一个好的接口来模拟ObjectQuery&lt;T&gt;。为了处理这种情况,我按照存储库模式创建了一个包装器类来封装我的ObjectContext,并创建了一个包装器类来封装ObjectQuery&lt;T&gt;

public interface IMyObjectQuery<T> : IOrderedQueryable<T>
{
    IMyObjectQuery<T> Include(string path);
}

public class MyObjectQuery<T> : IMyObjectQuery<T>
{
    private ObjectQuery<T> _query;

    public MyObjectQuery(ObjectQuery<T> query)
    {
        _query = query;
    }

    IMyObjectQuery<T> Include(string path)
    {
        //There is probably a better way to do this
        //but you get the idea
        return new MyObjectQuery(_query.Include(path));
    }

    //Implement IQueryable, IEnumerable...
}

然后是为您的 ObjectContext 实现一个存储库包装器的问题。 Here 是一个帮助您入门的链接。

添加如下内容:

public class MyRepository : IMyRespository
{
    ...
    public IMyObjectQuery<T> CreateQuery<T>()
    {
        return new MyObjectQuery(_context.CreateQuery<T>());
    }
    ...
}

这可能不是您正在寻找的简单解决方案,因为它不是一项简单的任务。我想您会发现,如果您不这样做,您将继续遇到编写测试的困难。

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多