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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With