Difference between EnsureSuccessStatusCode and Assert.Equal(HttpStatusCode.OK, response.StatusCode) in XUnit ASP.Net Core WebAPI Tests

Viewed 1089

I read in a Book (ISBN 1838550313, 9781838550318 S.315) that they check a WEB-API Request with both EnsureSuccessStatusCode() and Assert.Equal(HttpStatusCode.OK, ..) in one validation Method. But is the second Assert call not unnecessary to check if the HTTP-Status is 200 or not? What is the difference and what is the best practice?

enter image description here

1 Answers

HttpResponseMessage.EnsureSuccessStatusCode is implemented like this:

public HttpResponseMessage EnsureSuccessStatusCode()
{
    if (!IsSuccessStatusCode)
    {
        throw new HttpRequestException(…, inner: null, _statusCode);
    }
 
    return this;
}

So it just checks the value of IsSuccessStatusCode which is implemented like this:

public bool IsSuccessStatusCode
{
    get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); }
}

So a status code is considered to be successful, if it is in the range [200, 299]. This matches the definition of the HTTP status codes.

If the status code value is not a successful code, then the EnsureSuccessStatusCode method will throw an exception. So it is a quick way to stop the execution in cases where the request failed.

Asserting for equality with HttpStatusCode.OK checks if the status code is exactly 200. This also means that other successful codes would be rejected. Whether that is an appropriate thing to do depends on the API you are testing. Many RESTful APIs will often return different successful status codes depending on what happened. For example, an API might return “201 Created” to express that a resource has been created.

If the test wants to explicitly ensure that the response has a status code “200 OK”, then calling EnsureSuccessStatusCode is not needed. Otherwise, if you want to accept any successful status code, just calling EnsureSuccessStatusCode will be enough for the test since a thrown exception will usually fail the test.

Related