Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebApi testing - Asserting a request returns a 404 response

I have created an ApiController with the following method:

public User Get(int id)
{
    var user = DocumentSession.Load<User>(id);
    if(user!=null)
    {
        return Mapper.Map<User>(user); 
    }
    throw new HttpResponseException(HttpStatusCode.NotFound);
}

I am trying to write a test for this method which asserts that when an invalid id is passed to the function, it returns an appropriate 404 response.

at the moment I have:

[Test]
public void get_invalid_user_returns_404()
{
    Assert.Throws<HttpResponseException>(()=>_usersController.Get(1001));
} 

This works and passes, however it does not assert that it was a 404 response, simply that the right type of exception is thrown. What should I be doing here to assert that the result was a 404?

Thanks

like image 722
Paul Avatar asked Apr 28 '12 15:04

Paul


People also ask

How does Web API handle 404?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.


1 Answers

Assuming that you are using NUnit, you can do this like this:

[Test]
public void get_invalid_user_returns_404()
{
    HttpResponseException ex = Assert.Throws<HttpResponseException>(()=>_usersController.Get(1001));
    Assert.That(ex.Response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}

Should do the trick.

like image 69
tpeczek Avatar answered Feb 06 '23 09:02

tpeczek