.NET Core Xunit - IActionResult' does not contain a definition for 'StatusCode'

佐手、 提交于 2019-12-12 20:58:13

问题


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

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

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

I have my test case as:

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

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

Assert.Equal(500, response.StatusCode);

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

It throws me error:

'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?)

How can I resolve this?


回答1:


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

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
    var response = await _myController.DeleteUserId("");  //trying to pass empty id here

    // Assert
    Assert.IsType<ObjectResult>(response);

    var objectResponse = response as ObjectResult; //Cast to desired type

    Assert.Equal(500, objectResponse.StatusCode);
}



回答2:


You can use the return value of Assert.IsType<OkObjectResult>(response); to get the desired type:

var result = Assert.IsType<OkObjectResult>(response);
Assert.Equal(500, result.StatusCode)


来源:https://stackoverflow.com/questions/53083767/net-core-xunit-iactionresult-does-not-contain-a-definition-for-statuscode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!