NibblyPig
NibblyPig

Reputation: 52952

How can I test if a HttpResponseMessage is an ErrorResponse?

Writing a unit test to hit a controller, the code for the controller is:

public HttpResponseMessage InsertByKittyId(.....
    ...
    if (result.Success)
        return Request.CreateResponse(HttpStatusCode.OK);
    else
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new Exception(result.Message));

In my unit test it should generate an error response with the code:

var response = kittenController.InsertByKittenId(123);

Assert that response is an Error Response ?
var exceptionResult = (Error Response)response; ?
Assert.AreEqual("Bad Kitty", exceptionResult.Exception.Message);

Is there a way to write the two lines with a ?, or should I be checking to see if the response code is not 2xx instead and ignore the error aspect entirely? If so I will need to find a way to pull out the exception.

Edit:

I am wondering if there is a way to distinguish between CreateResponse and CreateErrorResponse rather than looking at the error code, because in some cases I want to attach an exception and in some cases it is not an 'error' per se.

Otherwise I could just do Request.CreateResponse(HttpStatusCode.InternalServerError);

However perhaps there is no difference?

Upvotes: 0

Views: 2793

Answers (2)

Kerim Emurla
Kerim Emurla

Reputation: 1151

There are 2 approaches.

The first is that you can check if the status code starts with "2", it would look something like this.

response.StatusCode.ToString().StartsWith("2");

The second approach is to use the IsSuccessStatusCode property of the response and check against that.

!response.IsSuccessStatusCode

Upvotes: 3

Yushatak
Yushatak

Reputation: 771

Assert.IsTrue(response.StatusCode.ToString()[0] == '2');

That'll check if it's a 2xx error.

Assert.IsTrue(response.IsSuccessStatusCode);

That'll check more generically if there was a failure.

Upvotes: 0

Related Questions