ASP.NET WebApi testing - Asserting a request returns a 404 response
asp.net-web-api
Solution
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.
Problem
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