如何测试返回 Ok(new { token = tokenStr }); 的函数
这是我的控制器类的函数,我想测试它,但我不知道为什么检查 OkObject
为空。我需要一些建议和解决这个问题的方法:
[HttpGet]
public async Task<IActionResult> LoginAsync(string phoneNumber, string pass)
{
User login = new User();
login.Phone = phoneNumber;
login.Password = pass;
IActionResult response = Unauthorized();
var user = await _loginService.AuthenticateUserAsync(login);
if(user != null)
{
var tokenStr = _loginService.GenerateJWT(user);
response = Ok(new { token = tokenStr });
}
return response;
}
我的测试功能是:
[Fact]
public async Task LoginAsync_ReturnOk()
{
var mock = new Mock<ILoginService>();
var controller = new LoginController(mock.Object);
var phone = "0123456789";
var pass = "abc123";
var okResult = await controller.LoginAsync(phone, pass);
Assert.IsType<OkObjectResult>(okResult as OkObjectResult);
}
我真的需要你的帮助。
This is my function of a controller class, I want to test this but I didn't have any idea to know why checking the OkObject
is null. I need some advice and a way to solve this:
[HttpGet]
public async Task<IActionResult> LoginAsync(string phoneNumber, string pass)
{
User login = new User();
login.Phone = phoneNumber;
login.Password = pass;
IActionResult response = Unauthorized();
var user = await _loginService.AuthenticateUserAsync(login);
if(user != null)
{
var tokenStr = _loginService.GenerateJWT(user);
response = Ok(new { token = tokenStr });
}
return response;
}
My test function is :
[Fact]
public async Task LoginAsync_ReturnOk()
{
var mock = new Mock<ILoginService>();
var controller = new LoginController(mock.Object);
var phone = "0123456789";
var pass = "abc123";
var okResult = await controller.LoginAsync(phone, pass);
Assert.IsType<OkObjectResult>(okResult as OkObjectResult);
}
I really need help from you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
测试失败,因为模拟的依赖项尚未配置为当前测试用例的预期行为。
指定测试用例的被测主体需要
为true,但未为测试用例配置
_loginService
这意味着被测主体将返回
UnauthorizedResult
这将导致
okResult as OkObjectResult
为 null需要安排测试,以便测试用例在执行时将按预期运行
并且因为有还有未经授权的响应的可能结果,这里是另一个测试用例来覆盖该控制器操作
The test is failing because the mocked dependency has not been configured to behave as expected for the current test case.
The subject under test for the stated test case needs
to be true but the
_loginService
was not configured for the test caseThat means that the subject under test will return
UnauthorizedResult
This will cause
okResult as OkObjectResult
to be nullThe test needs to be arranged so that the test case, when exercised, will behave as expected
And since there is also the possible outcome of having an unauthorized response, here is the other test case to cover that controller action