Web API Unit test for exception?

10,445

Leaving aside why your specific method isn't working, could I suggest that you don't bother testing that particular behaviour via an HTTPRequest - just test directly against the controller class:

[TestMethod]
[ExpectedException(typeof(HttpResponseException))]
public void Controller_Throws()
{
  try{
       //setup and inject any dependencies here, using Mocks, etc
       var sut = new TestController();
       //pass any required Action parameters here...
       sut.GetSomething();
     }
    catch(HttpResponseException ex)
    {
       Assert.AreEqual(ex.Response.StatusCode,
           HttpStatusCode.BadRequest,
           "Wrong response type");
throw;
     }
}

Since this way you are truly "unit testing" that behaviour on the controller, and avoiding any indirect tests

For example if your controller goes off and tries to hit a database before you throw your HttpResponseException, then you're not really testing the controller in isolation -- because if you did get an exception back you'd not be 100% certain what threw it.

By testing directly you can inject for e.g. Mock dependencies that will do nothing other than what you tell them to do.

Share:
10,445
James123
Author by

James123

Updated on June 09, 2022

Comments

  • James123
    James123 almost 2 years

    I wrote a unit test for exception. But looks like it is not working correctly. It is always saying '404 Not Found' Status. that means url request not found. If I paste same url on browser it HttpResponse.StatusCode says BAD REQUEST.

    I don't understand why it is not working for Unit test.

    [TestMethod()]
        public void GetTechDisciplinesTestException()
        {
            var config = new HttpSelfHostConfiguration("http://localhost:51546/");
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            using (var server = new HttpSelfHostServer(config))
            using (var client = new HttpClient())
            {
                server.OpenAsync().Wait();
                using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51546/api/techdisciplines/''"))
                using (var response = client.SendAsync(request).Result)
                {
                    //Here Response Status Code says 'Not Found', 
                    //Suppose to be 'Bad Request`
                    Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
                }
                server.CloseAsync().Wait();
            };
        }
    

    I tried with HttpSelfHostServer which works fine and it uses IISExpress.

     [TestMethod()]
        public void GetTechDisciplinesTestException()
        {
    
            using (var client = new HttpClient())
            {               
                using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51546/api/techdisciplines/''"))
                using (var response = client.SendAsync(request).Result)
                {
                    Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
                }               
            };
        }
    

    So I dont know HttpSelfHostServer is not wkring in the code? How to force HttpSelfHostServer to use IISExpress? How to deal this?