-1

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 ?

Abdul Manaf
  • 4,933
  • 8
  • 51
  • 95
  • see this => https://stackoverflow.com/a/19937421/5514820 – er-sho Feb 14 '19 at 10:44
  • Example from above link uses xunit framework – Abdul Manaf Feb 14 '19 at 10:50
  • @AbdulManaf This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The question in its current state is also incomplete and therefore unclear. Read [ask] and then edit the question to provide a [mcve] that can be used to reproduce the problem, allowing a better understanding of what is being asked. – Nkosi Feb 14 '19 at 11:32
  • In your example, controller has `get()` action. In the test you call `level0()`. – Nkosi Feb 14 '19 at 11:33

1 Answers1

5

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472