Search code examples
c#unit-testingmockingmoqxunit

UnitTests: UserManager<ApplicationUser> Mock Setup FindByIdAsync Returns NULL


In my test project i am using xUnit with Moq, in my controller test class i also need an object of type Mock<UserManager<ApplicationUser>> to get the current user informations.

That's why i am using Moq to Setup the async method FindByIdAsync the setup is configured like this :

public async Task EntrsAdd_ShouldReturnSuccessJsonResult_WhenModelIdIsNull()
{
    //Arrange
    var id = _fixture.Create<string>();
    ApplicationUser applicationUserMock = _fixture.Create<ApplicationUser>();
    var viewModelMock = _fixture.Create<AddOrUpdateEntrViewModel>();
    viewModelMock.Id = null;
    _userManager.Setup(u => u.FindByIdAsync(id))
        .Returns(Task.FromResult<ApplicationUser>(applicationUserMock));

    //Act
    var result = await _sutEntrsController.Add(viewModelMock).ConfigureAwait(false);
    int test = 0;
    //Assert
}

the method i am testing in the controller is:

public async Task<IActionResult> Add(AddOrUpdateEntrViewModel model)
{
    var user = await _userManager.FindByIdAsync(model.UsrId);

    var entr = _mapper.Map<Entr>(model);
    entr.Usr = $"{user.FirstName} {user.LastName}";

    if (model.Id is null)
    {
        await _entrService.AddAsync(entr);
    }
    else
    {
        await _entrService.UpdateAsync(entr);
    }

    return new JsonResult("success.");
}

Solution

  • The problem is that the setup uses the id variable and the corresponding property in the viewmodel is not set.

    Either set the correct id for UsrId on the ViewModelMock or relax the setup by using It.IsAny<string>():

    var viewModelMock = _fixture.Create<AddOrUpdateEntrViewModel>();
    viewModelMock.Id = null;
    viewModelMock.UsrId = id;
    

    or

    _userManager.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
        .Returns(Task.FromResult<ApplicationUser>(applicationUserMock));