Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 712
user1563677 Avatar asked Oct 31 '18 12:10

user1563677


1 Answers

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);
}
like image 190
Nkosi Avatar answered Sep 19 '22 01:09

Nkosi