.NET Core Xunit - IActionResult' 不包含 'StatusCode' 的定义

use*_*677 6 c# unit-testing xunit xunit.net asp.net-core

我有一个用 .NET Core 编写的 API,并使用 xUnit 来测试它们。

我在 API 中有我的方法:

[HttpDelete("api/{id}")]
public async Task<IActionResult> DeleteUserId(string id)
{
   try
    {
       //deleting from db       
    }
    catch (Exception ex)
    {           
        return StatusCode(500, ex.Message);
    }       
}
Run Code Online (Sandbox Code Playgroud)

当 null/empty id 传递给这个方法时,我想编写一个单元测试。

我有我的测试用例:

[Fact]
public void DeleteUserId_Test()
{
    //populate db and controller here

    var response= _myController.DeleteUserId("");  //trying to pass empty id here

    // Assert
    Assert.IsType<OkObjectResult>(response);
}
Run Code Online (Sandbox Code Playgroud)

如何检查从我的控制器方法调用返回的状态代码 500。就像是

Assert.Equal(500, response.StatusCode);
Run Code Online (Sandbox Code Playgroud)

在调试时,我可以看到响应具有StatusCode500 的结果返回类型(Microsoft.AspNetCore.Mvc.ObjectResult)。

但是当我尝试这样做时:

response.StatusCode
Run Code Online (Sandbox Code Playgroud)

它抛出我的错误:

“IActionResult”不包含“StatusCode”的定义,并且找不到接受“IActionResult”类型的第一个参数的扩展方法“StatusCode”(您是否缺少 using 指令或程序集引用?)

我该如何解决这个问题?

Nko*_*osi 11

将响应转换为所需类型并访问成员以进行断言。

请注意,测试操作返回 a Task,因此应将测试更新为异步

[Fact]
public async Task DeleteUserId_Test() {
    // Arrange
    // ...populate db and controller here

    // Act
    IActionResult response = await _myController.DeleteUserId("");  //trying to pass empty id here

    // Assert
    ObjectResult objectResponse = Assert.IsType<ObjectResult>(response); 
    
    Assert.Equal(500, objectResponse.StatusCode);
}
Run Code Online (Sandbox Code Playgroud)