'Mocked IPasswordHasher.HashPassword returns null

I have mocked IPasswordHasher<User>>:

private readonly Mock<IPasswordHasher<User>> _passwordHasher = new();

private readonly AccountController _accountController;

public AccountControllerTests()
{
    _accountController = new AccountController(_passwordHasher.Object);
}

Then I called this mocked AccountController inside my test method:

var result = _accountController.Login(dto);

And inside this method, hash is null, even though the user and dto.Password is not null and it works in "normal" (non-mocking) environment:

var hash = _passwordHasher.HashPassword(user, dto.Password);


Solution 1:[1]

You need to setup the method calls for the mocked object.

In the constructor of your test class, you could for example add

_passwordHasher
    .Setup(m => m.HashPassword(It.IsAny<User>(), It.IsAny<string>()))
    .Returns("Hash value");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fredirk