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

How to test a function that return Ok(new { token = tokenStr });

这是我的控制器 class 的功能,我想对此进行测试,但我不知道为什么检查 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);


        }

我真的需要你们的帮助。

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

被测试的主题为规定的测试用例需要

//...

 if(user != null)

//...

true 但未为测试用例配置 _loginService

//...

var user = await _loginService.AuthenticateUserAsync(login);

//...

也就是说被测对象会returnUnauthorizedResult

这将导致 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);
}