如何测试返回 Ok(new { token = tokenStr }); 的函数

发布于 2025-01-15 20:56:54 字数 1144 浏览 3 评论 0原文

这是我的控制器类的函数,我想测试它,但我不知道为什么检查 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哎呦我呸! 2025-01-22 20:56:54

测试失败,因为模拟的依赖项尚未配置为当前测试用例的预期行为。

指定测试用例的被测主体需要

//...

 if(user != null)

//...

true,但未为测试用例配置_loginService

//...

var user = await _loginService.AuthenticateUserAsync(login);

//...

这意味着被测主体将返回UnauthorizedResult

这将导致 okResult as OkObjectResultnull

需要安排测试,以便测试用例在执行时将按预期运行

[Fact]
public async Task LoginAsync_Should_Return_Ok() {
    // Arrange
    var mock = new Mock<ILoginService>();

    var user = new UserResult(); //Or what ever the actual user type is
    
    mock.Setup(_ => _.AuthenticateUserAsync(It.IsAny<User>()))
        .ReturnsAsync(user);

    string tokenStr = "some token value";

    mock.Setup(_ => _.GenerateJWT(user)).Returns(tokenStr);

    LoginController controller = new LoginController(mock.Object);

    string phone = "0123456789";
    string pass = "abc123";

    //Act
    IActionResult response = await controller.LoginAsync(phone, pass);

    //Assert
    OkObjectResult okResult = Assert.IsType<OkObjectResult>(response);
    
    //Optional: additional assertions for this test case
    dynamic value = okResult.Value;
    Assert.NotNull(value);

    string token = (string)value.token;
    Assert.Equal(token, tokenStr);
}

并且因为有还有未经授权的响应的可能结果,这里是另一个测试用例来覆盖该控制器操作

[Fact]
public async Task LoginAsync_Should_Return_Unauthorized() {
    //Arrange
    var mock = new Mock<ILoginService>();
    mock.Setup(_ => _.AuthenticateUserAsync(It.IsAny<User>()))
        .ReturnsAsync((UserResult)null); //Or what ever the actual user type is

    LoginController controller = new LoginController(mock.Object);

    string phone = "0123456789";
    string pass = "abc123";

    //Act
    IActionResult response = await controller.LoginAsync(phone, pass);

    //Assert
    Assert.IsType<UnauthorizedResult>(response);
}

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

//...

 if(user != null)

//...

to be true but the _loginService was not configured for the test case

//...

var user = await _loginService.AuthenticateUserAsync(login);

//...

That means that the subject under test will return UnauthorizedResult

This will cause okResult as OkObjectResult to be null

The test needs to be arranged so that the test case, when exercised, will behave as expected

[Fact]
public async Task LoginAsync_Should_Return_Ok() {
    // Arrange
    var mock = new Mock<ILoginService>();

    var user = new UserResult(); //Or what ever the actual user type is
    
    mock.Setup(_ => _.AuthenticateUserAsync(It.IsAny<User>()))
        .ReturnsAsync(user);

    string tokenStr = "some token value";

    mock.Setup(_ => _.GenerateJWT(user)).Returns(tokenStr);

    LoginController controller = new LoginController(mock.Object);

    string phone = "0123456789";
    string pass = "abc123";

    //Act
    IActionResult response = await controller.LoginAsync(phone, pass);

    //Assert
    OkObjectResult okResult = Assert.IsType<OkObjectResult>(response);
    
    //Optional: additional assertions for this test case
    dynamic value = okResult.Value;
    Assert.NotNull(value);

    string token = (string)value.token;
    Assert.Equal(token, tokenStr);
}

And since there is also the possible outcome of having an unauthorized response, here is the other test case to cover that controller action

[Fact]
public async Task LoginAsync_Should_Return_Unauthorized() {
    //Arrange
    var mock = new Mock<ILoginService>();
    mock.Setup(_ => _.AuthenticateUserAsync(It.IsAny<User>()))
        .ReturnsAsync((UserResult)null); //Or what ever the actual user type is

    LoginController controller = new LoginController(mock.Object);

    string phone = "0123456789";
    string pass = "abc123";

    //Act
    IActionResult response = await controller.LoginAsync(phone, pass);

    //Assert
    Assert.IsType<UnauthorizedResult>(response);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文