moq回调使linq抛出异常

时间:2014-11-11 18:43:49

标签: c# entity-framework moq

我正在使用Moq和EF6。

我需要查询一个表,如果表中的日期少于5个,我需要添加更多。

所以,我在我的代码中这样做:

    public void FillPartyList(ObservableCollection<Party> argPartyList)
    {
        argPartyList.Clear();

        using (IPartyTrackerDataAccess localDb = Locator.Resolve<IPartyTrackerDataAccess>())
        {
            InitializeDates(localDb);

            var localList = (from tempList in localDb.Parties
                             where tempList.PartyDate >= DateTime.Now.Date
                             select tempList);

            foreach (Party currentParty in localList)
            {
                argPartyList.Add(currentParty);
            }
        }

    }

Inside&#34; InitializeDates&#34;我查询数据库以查看有多少日期,然后添加足够的日期5.有关于创建日期的规则[例如只在星期五或星期六等]所以这不是微不足道的。然后,当方法返回时,我从数据库中获取完整列表并将其添加到参数中。

当我尝试测试时,问题出现了。这是我的考验。

    public void TestInitializeDates()
    {
        //Expected data
        int callCount = 0;
        int addParty = 0;
        int saveChanges = 0;
        ObservableCollection<Party> PartyList = new ObservableCollection<Party>();

        //Mock data
        IQueryable<Party> partyData = new List<Party>().AsQueryable();
        IQueryable<SystemSetting> settingsData = new List<SystemSetting>().AsQueryable();

        //Setup mock
        Mock<PartyTrackerEntities> mockContext = SetupDbContext();

        SetupApplicationSettings(mockContext, settingsData);
        SetupPartyDbSet(mockContext, partyData);

        Locator.Register<IApplicationSettings, ApplicationSettings>();

        //If I keep the following line I get an exception when querying the "database" for parties.
        mockContext.Setup(m => m.Parties.Add(It.IsAny<Party>())).Callback(() => addParty = callCount++);
        mockContext.Setup(m => m.SaveChanges()).Callback(() => saveChanges = callCount++);

        //Run tests

        PartyTrackerModel localModel = new PartyTrackerModel();

        localModel.FillPartyList(PartyList);

        Assert.AreEqual(1, callCount);
        Assert.AreEqual(0, saveChanges);
    }

    private Mock<DbSet<Party>> SetupPartyDbSet(Mock<PartyTrackerEntities> argDbContext, IQueryable<Party> argPartyData)
    {

        //Mock objects
        Mock<DbSet<Party>> mockPartySet = new Mock<DbSet<Party>>();

        mockPartySet.As<IQueryable<Party>>().Setup(m => m.Provider).Returns(argPartyData.Provider);
        mockPartySet.As<IQueryable<Party>>().Setup(m => m.Expression).Returns(argPartyData.Expression);
        mockPartySet.As<IQueryable<Party>>().Setup(m => m.ElementType).Returns(argPartyData.ElementType);
        mockPartySet.As<IQueryable<Party>>().Setup(m => m.GetEnumerator()).Returns(argPartyData.GetEnumerator());

        argDbContext.Setup(m => m.Parties).Returns(mockPartySet.Object);

        return mockPartySet;
    }
编辑:我心烦意乱,没有完成这个问题。

一切正常,直到我添加增加计数器的设置,然后InitializeDates()中的Linq失败。

如何递增计数器并保留DbSet&lt;&gt;嘲弄吗?我如何查询&#34;数据库&#34;并仍然计算添加的调用?如果我设置Context.Parties.Add()来计算调用,则linq查询会爆炸。

我做错了什么?

编辑:添加InitializeDates()。注意:在添加Moq.Callback之前,这些都没有问题。

    private static void InitializeDates(IPartyTrackerDataAccess argLocalDb)
    {
        IApplicationSettings localAppSettings = Locator.Resolve<IApplicationSettings>();

        //using (PartyTrackerEntities LocalDb = new PartyTrackerEntities())
        {
            //TODO: Move this code to the PartyTrackerDb class.
            //Technically this would communicate with the database and 
            //make sure there are at least 5 parties in the future.
            var SqlPartyList = from LinqList in argLocalDb.Parties
                               where LinqList.PartyDate >= DateTime.Now.Date
                               select LinqList;
            List<Party> PartyList;
            try
            {
                PartyList = SqlPartyList.OrderByDescending(argOrder => argOrder.PartyDate).Take(5).ToList();
            }
            catch (SqlException)
            {
                //MessageBox.Show("Cannot connect to database. Please ensure that SQLServer is running and accessable from this machine.");
                throw;
            }

            if (PartyList.Count < 5)
            {
                DateTime MaxPartyDate = PartyList.Count <= 0
                                            ? DateTime.Now.Date.AddDays(-1)
                                            : PartyList.Max(argMaxDate => argMaxDate.PartyDate);

                //<= 4 because  PartyList.Count is zero-based so this is 5 parties.
                for (int ShortDayCount = PartyList.Count; ShortDayCount <= 4; ShortDayCount++)
                {
                    int dateOffset;
                    decimal coupleDonation;
                    decimal singleMaleDonation;
                    decimal singleFemaleDonation;
                    decimal sponsoredMaleDonation;
                    if (MaxPartyDate.DayOfWeek == DayOfWeek.Friday) //If the last party in the list is on a Friday, then we need to add a Saturday
                    {
                        //Get the Donation amounts
                        //Get Saturday Donations
                        coupleDonation = localAppSettings.SatCoupleDonation;
                        singleMaleDonation = localAppSettings.SatSingleMaleDonation;
                        singleFemaleDonation = localAppSettings.SatSingleFemaleDonation;
                        sponsoredMaleDonation = localAppSettings.SatSponsoredMaleDonation;

                        //Add Sat
                        dateOffset = 1;
                    }
                    else //Otherwise we need to add a Friday
                    {
                        //Get the Donation amounts
                        //Get Friday Donations
                        coupleDonation = localAppSettings.FriCoupleDonation;
                        singleMaleDonation = localAppSettings.FriSingleMaleDonation;
                        singleFemaleDonation = localAppSettings.FriSingleFemaleDonation;
                        sponsoredMaleDonation = localAppSettings.FriSponsoredMaleDonation;

                        if (MaxPartyDate.DayOfWeek == DayOfWeek.Saturday)
                        {
                            dateOffset = 6;
                        }
                        else
                        {
                            dateOffset = 5 - (int)MaxPartyDate.DayOfWeek;
                        }
                    }
                    Party NewParty = new Party
                    {
                        PartyDate = MaxPartyDate.AddDays(dateOffset),
                        CoupleDonation = coupleDonation,
                        SingleMaleDonation = singleMaleDonation,
                        SingleFemaleDonation = singleFemaleDonation,
                        SponsoredMaleDonation = sponsoredMaleDonation
                    };

                    argLocalDb.Parties.Add(NewParty);

                    MaxPartyDate = NewParty.PartyDate;
                }

                argLocalDb.SaveChanges();

            }
        }
    }

0 个答案:

没有答案