.NET Core Xunit-IActionResult'不包含'StatusCode'的定义 [英] .NET Core Xunit - IActionResult' does not contain a definition for 'StatusCode'

查看:82
本文介绍了.NET Core Xunit-IActionResult'不包含'StatusCode'的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用.NET Core编写的API,并使用xUnit对其进行了测试.

I have an API written in .NET Core and using xUnit to test those.

我在API中的方法如下:

I have my method in API as:

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

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

I want to write a unit test when null/empty id passed to this method.

我的测试用例为:

[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);
}

如何检查此处的控制器方法调用返回的状态码500.像

How can I check the status code 500 is returned from my controller method call here. Something like

Assert.Equal(500, response.StatusCode);

在调试时,我可以看到响应的结果返回类型(Microsoft.AspNetCore.Mvc.ObjectResult)的状态码为500.

While debugging I can see response has Result return type (Microsoft.AspNetCore.Mvc.ObjectResult) which has StatusCode as 500.

但是当我尝试这样做时:

But when I try to do this:

response.StatusCode

它引发了我错误:

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

'IActionResult' does not contain a definition for 'StatusCode' and no extension method 'StatusCode' accepting a first argument of type 'IActionResult' could be found (are you missing a using directive or an assembly reference?)

我该如何解决?

推荐答案

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

Cast the response to the desired type and access the member for assertion.

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

Note that the tested action returns a Task, so the test should be updated to be async

[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);
}

这篇关于.NET Core Xunit-IActionResult'不包含'StatusCode'的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆