你如何在EntityFramework中使用FirstOrDefault?

时间:2013-11-03 14:42:05

标签: c# entity-framework unit-testing microsoft-fakes

使用Microsoft Fakes和Entityframework,我正在尝试为FirstOrDefault()创建一个垫片。我有一个方法,我想进行单元测试,看起来像这样:

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密钥)调用。

我设置了假货并为数据库和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不能为null。   参数名称:参数     来源= System.Core程序     PARAMNAME =参数     堆栈跟踪:          at System.Linq.Expressions.Expression.RequiresCanRead(Expression expression,String paramName)          在System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase方法,ExpressionType nodeKind,Expression arg,ParameterInfo pi)          at System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase方法,ExpressionType nodeKind,ReadOnlyCollection 1& arguments) at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable 1个参数)          在System.Linq.Expressions.Expression.Call(表达式实例,MethodInfo方法,Expression []参数)          在System.Linq.Queryable.FirstOrDefault [TSource](IQueryable 1 source, Expression 1谓词)          在Controllers \ Api \ TitlesController.cs中的WebSite.Web.Controllers.Api.TitlesController.GetEntityByKey(Guid键):第42行          在System.Web.Http.OData.EntitySetController`2.Get(TKey键)          在TitlesController_Tests.cs中的WebSite.Web.Tests.TitlesController_Tests.Get_ReturnsOneItem_Test():第96行     InnerException:

如何让FirstOrDefault返回一些内容?它甚至不必执行查询,我想要测试的是我调用FirstOrDefault并返回它返回的值,或者当它返回null时抛出异常。

1 个答案:

答案 0 :(得分:-2)

阅读你的帖子我认为我遇到了同样的问题,我不会复制并粘贴我找到并为我工作的解决方案,而是我给你的URL:

http://mylifeandcode.blogspot.com/2012/10/unit-testing-with-mock-entity-framework.html

玩得开心!!!