简体   繁体   中英

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

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?

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

    // Assert
    ObjectResult objectResponse = Assert.IsType<ObjectResult>(response); 
    
    Assert.Equal(500, objectResponse.StatusCode);
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM