jeudi 26 décembre 2019

Mocking of Where method in Data Repository is returning null at its actual implementation in repository

I have written a test for edit model of a class in EF core.

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;
        }
}

I want to test this method using xUnit and Moq and I have also written a method for it as below.

[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);
}

But here, the Where method is returning null

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

I am getting var expense null in above code.

Please suggest what should I include in the code to get the value in above var expense?

To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?

Aucun commentaire:

Enregistrer un commentaire