使用 Microsoft Fakes 和 Entityframework,我正在尝试为 FirstOrDefault() 创建一个 shim。我有一个方法,我想进行单元测试,如下所示:
protected override v_Titles GetEntityByKey(Guid key)
{
var result = Context.v_Titles.FirstOrDefault(t => t.Id == key);
if ( result == null )
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return result;
}
由公共方法 Get(Guid key) 调用。
我设置了假货并填充了数据库和 v_Titles 集合:
public void SetUp()
{
_titles = new List<v_Titles>
{
new v_Titles
{
Id = new Guid(1,0,0,0,0,0,0,0,0,0,0),
PostedDate = new DateTime(2013,1,1),
Title = "2013-01-01"
},
new v_Titles
{
Id = new Guid(2,0,0,0,0,0,0,0,0,0,0),
PostedDate = new DateTime(2013,5,23),
Title = "2013-05-23"
},
new v_Titles
{
Id = new Guid(3,0,0,0,0,0,0,0,0,0,0),
PostedDate = new DateTime(2013,8,10),
Title = "2013-08-10"
}
};
_shimTitles = new ShimDbSet<v_Titles>();
_shimTitles.Bind(_titles);
...
_databaseShim = new shimDatabaseEntities();
_databaseShim.v_TitlesGet = () => _shimTitles.Instance;
_target = new TitlesController
{
Context = _databaseShim.Instance
};
在 ... 的进一步位置,我尝试了以下垫片以使 FirstOrDefault 工作:
System.Linq.Fakes.ShimEnumerableQuery<v_Titles>.AllInstances.GetEnumerator = (a) =>
{ return _titles.GetEnumerator(); };
System.Linq.Fakes.ShimQueryable.FirstOrDefaultOf1IQueryableOfM0<v_Titles>((a) =>
{
return _titles.FirstOrDefault();
});
databaseEntities.AllInstances.v_TitlesGet = (a) => _shimTitles.Instance;
我的单元测试如下所示:
[TestMethod]
public void Get_ReturnsOneItem_Test()
{
using (ShimsContext.Create())
{
var expected = new Guid(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
SetUp();
var result = _target.Get(expected);
}
}
运行测试时,我在 .FirstOrDefault() 调用中遇到以下异常。
System.ArgumentNullException 未被用户代码处理 HResult=-2147467261 Message=Value 不能为空。参数名称:参数 Source=System.Core ParamName=arguments StackTrace:在 System.Linq.Expressions.Expression.RequiresCanRead(Expression expression, String paramName) at System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg , ParameterInfo pi) 在 System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase 方法, ExpressionType nodeKind, ReadOnlyCollection
1& arguments) at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable
1 arguments) 在 System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments) 在 System. Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression
1 谓词)在 WebSite.Web.Controllers.Api.TitlesController.GetEntityByKey(Guid key) 在 Controllers\Api\TitlesController.cs:line 42 at System.Web.Http.OData.EntitySetController`2.Get(TKey key) 在网站TitlesController_Tests.cs 中的 .Web.Tests.TitlesController_Tests.Get_ReturnsOneItem_Test():第 96 行 InnerException:
如何让 FirstOrDefault 返回一些东西?它甚至不必执行查询,我想要测试的是我正在调用 FirstOrDefault 并返回它返回的值或在返回 null 时引发异常。