Home > Enterprise >  Mocked IPasswordHasher.HashPassword returns null
Mocked IPasswordHasher.HashPassword returns null

Time:04-26

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

CodePudding user response:

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");
  • Related