数据存储库中的Where方法的模拟在存储库中的实际实现中返回null

时间:2019-12-26 08:27:41

标签: asp.net testing null moq xunit

我已经为EF核心中的类的编辑模型编写了一个测试。

public async Task<Expense> EditExpense(Expense model)
{
        var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();

        if(expense != null)
        {
            expense.ForEach(x =>
            {
                x.Name = model.Name;
                x.AddedOn = model.AddedOn;
                x.Amount = model.Amount;
                x.Type = model.Type;
                x.SplitOption = model.SplitOption;
                x.Notes = model.Notes;
                x.IsGroupExpense = model.IsGroupExpense;
            });

            return expense.FirstOrDefault();
        }
        else
        {
            return null;
        }
}

我想使用xUnit和Moq来测试此方法,并且还为它编写了如下方法。

[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
        var expenseCurrent = new Expense()
        {
            Id = 5,
            Name = "Test Expense",
            Amount = 1500,
            AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
            AddedOn = DateTime.Now,
            Notes = "",
            IsDeleted = false,
            IsGroupExpense = false,
            SplitOption = 1,
            Type = 0
        };

        var expenseList = (new List<Expense>{ expenseCurrent });

        var expenseAfterEdit = new Expense()
        {
            Id = 5,
            Name = "Test Expense Edited",
            Amount = 2000,
            AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
            AddedOn = DateTime.Now,
            Notes = "Edited !!!",
            IsDeleted = false,
            IsGroupExpense = true,
            SplitOption = 2,
            Type = 0
        };

        _dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);

        var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
        Assert.Equal(expenseEdited, expenseAfterEdit);
}

但是在这里,Where方法返回null

public async Task<Expense> EditExpense(Expense model)
{
        var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository 
}

在上面的代码中我得到的var费用为空。

请提出我应该在代码中包括哪些内容才能获得上述var费用中的值?

要测试此方法,我想创建一个将要更新的伪造数据。请建议如何正确编写此内容?

0 个答案:

没有答案