Search code examples
c#unit-testingasp.net-web-apinunitassert

How to check 200 ok using NUnit


I have created a web API that returns 200 ok response.

 public IHttpActionResult get()
 {
    return Ok();
 }

Also, I have created a test project using the NUnit framework.

var controller = new StatusController();
var result= controller.level0() as OkNegotiatedContentResult<object>;
IHttpActionResult actionResult = controller.level0();
Assert.AreEqual(HttpStatusCode.OK, actionResult);

But i got error like this

Expected: OK
  But was:  <System.Web.Http.Results.OkResult>

When I am trying to debug the 'actionResult' variable, it contains one error

Request = '((System.Web.Http.Results.OkResult)actionResult).Request' threw an exception of type 'System.InvalidOperationException'

How do I check my http status code ?


Solution

  • Based on the provided controller you appear to be casting the result to the wrong type.

    Ok() returns an instance of OkResult

    check the return type to verify that action under test behaves as expected.

    //Arrange
    var controller = new StatusController();
    
    //Act
    IHttpActionResult actionResult = controller.get();
    
    //Assert
    Assert.IsInstanceOf<OkResult>(actionResult);
    

    Reference Unit Testing Controllers in ASP.NET Web API 2