Search code examples
c#asp.netunit-testingmoqxunit

ASP.NET Mock Failed SignInResult is returning Null


In my test project i am using xUnit with Moq.

now i want to unit test these piece of code in the controller:

var result = await _signInManager.PasswordSignInAsync(model.Email,
                                                      model.Password, 
                                                      model.RememberMe, 
                                                      lockoutOnFailure: false);

if (result.Succeeded) {}

in order to do that, i'm need to mock the PasswordSignInAsync function so it returns a success/failed SignInResult

the setup in the unit test class:

//Arrange
var _loginViewModel = _fixture.Build<LoginViewModel>()
    .OmitAutoProperties().With(l => l.Email).Create();
var applicationUser = _fixture.Create<ApplicationUser>();
_signInManager.Setup(s => s
                .PasswordSignInAsync(applicationUser,
                        _loginViewModel.Password,
                        _loginViewModel.RememberMe,
                        false))
                .Returns(Task.FromResult(SignInResult.Success));
//Act
IActionResult result = await _sutAccountController.Login(_loginViewModel, null);
ViewResult? viewResult = result as ViewResult;

but when debbuging the test method, the funtion PasswordSignInAsync always returns null

------ Edit: Removing unnecessary code

Any idea? Thanks


Solution

  • You are mocking the wrong overload of PasswordSignInAsync, you have mocked the one that takes a user object instead of the one that takes the email address which is what is actually being called in your first snippet.

    Try this instead:

    _signInManager.Setup(s => s
        .PasswordSignInAsync(
            It.IsAny<string>(), // Feel free to replace this with an actual email
            _loginViewModel.Password,
            _loginViewModel.RememberMe,
            false))
        .ReturnsAsync(SignInResult.Success);