gpt4 book ai didi

c# - 测试验证方法

转载 作者:行者123 更新时间:2023-12-02 03:21:27 25 4
gpt4 key购买 nike

我目前正在尝试学习单元测试,并且我已经在 ASP.NET Core 中创建了项目,因此我可以学习在真实示例上进行测试。我想在 API Controller 中测试验证方法的快乐路径,因此它将返回 OkObjectResult。

到目前为止我所拥有的。

我想测试的 Controller 方法

        [AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]User userParam)
{
var user = _userService.Authenticate(userParam.Nickname,
userParam.Password).Result;

if(user == null)
{
return BadRequest(
new { message = "Username or password is incorrect " }
);
}

return Ok(user);
}

验证实现 IUserService 的类中的方法:

public async Task<User> Authenticate(string nickname, string password)
{
var user = _repository.User.GetAllUsersAsync().Result.SingleOrDefault(u => u.Nickname == nickname && u.Password == password);

if(user == null)
{
return null;
}

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescription = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserId.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

var token = tokenHandler.CreateToken(tokenDescription);
user.Token = tokenHandler.WriteToken(token);

try
{
await _repository.User.UpdateUserAsync(user);

user.Password = null;

return user;
}
catch (Exception e)
{
return user;
}

}

我的单元测试:

        [Fact]
public void Authenticate_WhenCalled_ReturnsOk()
{
//Arrange
var mockService = new Mock<IUserService>();
var user = new User()
{
UserId = 4,
IsAdmin = true,
Token = "12983912803981",
IsLogged = true,
MessagesSent = null,
MessagesReceived = null,
Nickname = "test3",
Password = "Str0ngP@ssword123",
UserChannels = null
};

var controller = new UsersController(_repository, _logger, mockService.Object);

//Act
var result = controller.Authenticate(user);

//Assert
var okResult = result.Should().BeOfType<OkObjectResult>();
}

但是,单元测试返回 BadRequest,而不是预期的 OkObjectResult。这意味着该用户可能实际上为空并且抛出了 BadRequest。我应该模拟 Repository 而不是 IUserService 吗?

最佳答案

实际上,你做得很好,并且把所有事情都做得很完美(真正使用 AAA 的开发人员太少了,这非常令人难过),但请记住,Mock 默认返回 default(T) 值。因此,您的 Authenticate 方法被模拟并返回 default(User) ,即 null。只需让它返回您的 stub 用户即可:

 var mockService = new Mock<IUserService>();
var user = new User()
{
UserId = 4,
IsAdmin = true,
Token = "12983912803981",
IsLogged = true,
MessagesSent = null,
MessagesReceived = null,
Nickname = "test3",
Password = "Str0ngP@ssword123",
UserChannels = null
};
mockService.Setup(x=> x.Authenticate(It.IsAny(), It.IsAny())).Returns(user);

或者@xander提出的更严格版本:

 mockService.Setup(x=> x.Authenticate("test3", "Str0ngP@ssword123")).Returns(user);

它还会检查您是否确实使用了传入 User 的值,而不仅仅是盲目地返回 Ok()。

关于c# - 测试验证方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54638806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com