Resolved Issue can't mock

bosna

New member
Joined
Jan 20, 2024
Messages
2
Programming Experience
Beginner
Hello,

I have issue with Xunit in .Net core testing. I can't make mocking of my method GetBudgetByUser() it returns 0. I have tried all possible solutions but never found solution and I sit in stuck.
C#:
[Fact]
public async Task GetBudgetsByUser_ReturnsBudgets_WhenBudgetsFound()
{
    // Arrange
    BudgetGet budgetGet = new() { UserId = "user-id" };

    var mock = GetFakeBudgetsList().BuildMock().BuildMockDbSet();
    _contextMock.Setup(x => x.Budgets).Returns(mock.Object);

    // Act
    BudgetController controller = new BudgetController(_contextMock.Object, _userManagerMock.Object);
    var responseResult = await controller.GetBudgetsByUser(budgetGet);

    // Assert
    Assert.NotNull(responseResult);
    Assert.Equal(2, responseResult.Value.Count());
}
And my controller method
C#:
[HttpPost]
[Route("list")]
public async Task<ActionResult<IEnumerable<BudgetResponse>>> GetBudgetsByUser(BudgetGet budgetGetModel)
{
    if (budgetGetModel is null)
    {
        return BadRequest();
    }

    List<Budget> budgets = await _context.Budgets.Where(x => x.ApplicationUser.Id == budgetGetModel.UserId).ToListAsync(); // Issue is here it returns 0. Bud should return mock.object list

    if(budgets is null)
    {
        return NotFound();
    }

    List<BudgetResponse> responseList = budgets.Select(b => new BudgetResponse {
        BudgetId = b.BudgetID,
        Title = b.Title,
        Created = b.Created,
        Modified = b.Modified,
        }).ToList();

    return responseList;
}
If some have quick solution please write a comment
 
Last edited by a moderator:
XUnit is not used for mocking. XUnit is used for unit testing.
 
Anyway, do you absolutely know that this returns two objects that has UserId set to "user-id"?
C#:
var mock = GetFakeBudgetsList().BuildMock().BuildMockDbSet();
 
Hi skydiver,
Thanks, you have right I was need to make same user-id like in FakeData. So it was the solution.
 
Back
Top Bottom