Entity framework 4 如何创建ObjectQuery以测试EF4';包括';方法
我们正在使用EF4并为DAL层创建测试用例(DAL层具有linq查询)。我们使用TypeMock作为模拟框架。为了进行测试,我们正在创建Entity framework 4 如何创建ObjectQuery以测试EF4';包括';方法,entity-framework-4,typemock-isolator,Entity Framework 4,Typemock Isolator,我们正在使用EF4并为DAL层创建测试用例(DAL层具有linq查询)。我们使用TypeMock作为模拟框架。为了进行测试,我们正在创建ObjectContext的Fakecontext和mockCreateObjectSet方法,如下所示: Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable
ObjectContext
的Fakecontext和mockCreateObjectSet
方法,如下所示:
Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable());
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;
}
Isolate.WhenCalled(()=>fakeContext.Context.CreateObjectSet)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable());
上述措施效果良好。问题是当我们试图使用“include”包含相关表时。我们将include方法扩展如下:
Isolate.WhenCalled(() => fakeContext.Context.CreateObjectSet<User>)).WillReturnCollectionValuesOf(fakeUsers.AsQueryable());
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;
}
公共静态IQueryable包含(此IQueryable源、表达式属性)
{
var objectQuery=源作为objectQuery;
if(objectQuery!=null)
{
var propertyPath=GetPropertyPath(属性);
返回objectQuery.Include(propertyPath);
}
返回源;
}
因此,在上面的Include
方法中,源类型应该是ObjectQuery
。但正如我们模拟的CreateObjectSet
一样,Include
方法中的源类型是Collection.Generic.List
类型。请让我们知道,在上述情况下,我们应该如何嘲笑。你的及时帮助将是非常值得赞赏的。谢谢在编写单元测试时可能很难使用。不幸的是,正如您所发现的,对于ObjectQuery
,没有一个很好的模拟接口。为了处理这个场景,我按照存储库模式创建了一个包装类来封装我的ObjectContext
,并创建了一个包装类来封装ObjectQuery
:
公共接口IMyObjectQuery:IOrderedQueryable
{
IMyObjectQuery包含(字符串路径);
}
公共类MyObjectQuery:IMyObjectQuery
{
私有对象查询;
公共MyObjectQuery(ObjectQuery)
{
_查询=查询;
}
IMyObjectQuery包含(字符串路径)
{
//也许有更好的方法可以做到这一点
//但你明白了
返回新的MyObjectQuery(_query.Include(path));
}
//实现IQueryable、IEnumerable。。。
}
然后是为ObjectContext实现存储库包装器的问题。是一个让你开始的链接
添加如下内容:
public class MyRepository : IMyRespository
{
...
public IMyObjectQuery<T> CreateQuery<T>()
{
return new MyObjectQuery(_context.CreateQuery<T>());
}
...
}
公共类MyRepository:IMyRespository
{
...
公共IMyObjectQuery CreateQuery()
{
返回新的MyObjectQuery(_context.CreateQuery());
}
...
}
这可能不是您正在寻找的简单解决方案,因为它不是一项琐碎的任务。我想你会发现,如果你不这样做,你将继续遇到写测试的困难。你能至少正确地设置一个问题的格式吗?可能是重复的