Here is my test with a new Mock and its setup:
[Fact]
public async Task RegisterUser_MustReturnPhoneNumberError2()
{
var userRepository = new Mock<IUserRepository>()
.Setup(_ => _.GetUserByUsernameAndPassword(It.IsAny<string>(), It.IsAny<string>()))
.Returns(new User
{
Password = "b",
EmailAddress = "asdadsa!yaho",
Name = "asa"
});
var userService = new UserService(new Mock<IUserRepository>().Object);
var expectation = new UserResponseDto
{
Status = new StatusMaker().ErrorStatus("TEXT")
};
var a = new UserCredentialRequestDto
{
EmailAddress = "a",
Password = "b",
PhoneNumber = "c"
};
var res = await userService.LoginUser(a);
Assert.Equal(expectation.Status.Message, res.Status.Message);
}
and here is the real method:
public async Task<UserResponseDto> LoginUser(UserCredentialRequestDto userCredential)
{
var user = _userRepository.GetUserByUsernameAndPassword(userCredential.PhoneNumber,
userCredential.Password.DoHash());
// If user is Null
#region Error Status
if (user is null)
{
return new UserResponseDto
{
Status = new StatusMaker().ErrorStatus("ABCD")
};
}else{
return new UserResponseDto
{
Status = new StatusMaker().ErrorStatus("TEXT")
};
}
After I run debug the test, the GetUserByUsernameAndPassword()
function would be null
again. Why the return of GetUserByUsernameAndPassword()
would be null
even after Mock Setup?
CodePudding user response:
You're passing a newly instantiated Mock of IUserRepository.
Try the following
var userRepository = new Mock<IUserRepository>()
.Setup(_ => _.GetUserByUsernameAndPassword(It.IsAny<string>(), It.IsAny<string>()))
.Returns(new User
{
Password = "b",
EmailAddress = "asdadsa!yaho",
Name = "asa"
});
var userService = new UserService(userRepository.Object);