如何伪造 EntityFramework.Extended FutureQuery?
How to fake EntityFramework.Extended FutureQuery?
我想设置一个假的存储库。
public class FooRepo {
public FutureFoo<Foo> GetById(int id) {
var foo = new Foo();
return new FutureValue(foo);
}
public FutureQuery<Foo> GetByCategory(int categoryId) {
var foos = new[] { new Foo(), new Foo() new Foo() };
return //what goes here?
}
}
这样做的目的是编写数据相关测试,而不依赖于任何数据库连接。这对于 FutureValue<>
类型来说非常简单,因为它提供了一个接受直接对象的构造函数。但是 FutureQuery<>
的构造函数接受参数 IQueryable query, Action loadAction
我可以忽略loadAction
吗?
如:new FutureQuery<Foo>(foos.AsQueryable(), () => { });
或者解决这个问题的正确方法是什么?
强制解:
(FutureQuery<Foo>) Activator.CreateInstance(typeof(FutureQuery<Foo>),
BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[] { foos.AsQueryable(), null }, null);
摘自 FutureQueryBase.GetResult()
:
/// <summary>
/// Gets the result by invoking the <see cref="LoadAction"/> if not already loaded.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> that can be used to iterate through the collection.
/// </returns>
protected virtual IEnumerable<T> GetResult()
{
if (IsLoaded)
return _result;
// no load action, run query directly
if (LoadAction == null)
{
_isLoaded = true;
_result = _query as IEnumerable<T>;
return _result;
}
// invoke the load action on the datacontext
// result will be set with a callback to SetResult
LoadAction.Invoke();
return _result ?? Enumerable.Empty<T>();
}
您应该为加载操作传递一个 null
,除非您想通过 SetResult(ObjectContext, DbDataReader)
显式更新 _result
。
我想设置一个假的存储库。
public class FooRepo {
public FutureFoo<Foo> GetById(int id) {
var foo = new Foo();
return new FutureValue(foo);
}
public FutureQuery<Foo> GetByCategory(int categoryId) {
var foos = new[] { new Foo(), new Foo() new Foo() };
return //what goes here?
}
}
这样做的目的是编写数据相关测试,而不依赖于任何数据库连接。这对于 FutureValue<>
类型来说非常简单,因为它提供了一个接受直接对象的构造函数。但是 FutureQuery<>
的构造函数接受参数 IQueryable query, Action loadAction
我可以忽略loadAction
吗?
如:new FutureQuery<Foo>(foos.AsQueryable(), () => { });
或者解决这个问题的正确方法是什么?
强制解:
(FutureQuery<Foo>) Activator.CreateInstance(typeof(FutureQuery<Foo>),
BindingFlags.NonPublic | BindingFlags.Instance, null,
new object[] { foos.AsQueryable(), null }, null);
摘自 FutureQueryBase.GetResult()
:
/// <summary>
/// Gets the result by invoking the <see cref="LoadAction"/> if not already loaded.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> that can be used to iterate through the collection.
/// </returns>
protected virtual IEnumerable<T> GetResult()
{
if (IsLoaded)
return _result;
// no load action, run query directly
if (LoadAction == null)
{
_isLoaded = true;
_result = _query as IEnumerable<T>;
return _result;
}
// invoke the load action on the datacontext
// result will be set with a callback to SetResult
LoadAction.Invoke();
return _result ?? Enumerable.Empty<T>();
}
您应该为加载操作传递一个 null
,除非您想通过 SetResult(ObjectContext, DbDataReader)
显式更新 _result
。