sunil sunil - 1 year ago 184
C# Question

How do I unit test web api action method when it returns IHttpActionResult?

Let's assume this is my action method

public IHttpActionResult Get(int id)
var status = GetSomething(id);
if (status)
return Ok();
return NotFound();

Test will be

var httpActionResult = controller.Get(1);

How do I check my http status code after this?

Answer Source

Here Ok() is just a helper for the type OkResult which sets the response status to be you can just check if the instance of your action result is an OkResult...some examples(written in XUnit):

// if your action returns: NotFound()
IHttpActionResult actionResult = valuesController.Get(10);

// if your action returns: Ok()
actionResult = valuesController.Get(11);

// if your action was returning data in the body like: Ok<string>("data: 12")
actionResult = valuesController.Get(12);
OkNegotiatedContentResult<string> conNegResult = Assert.IsType<OkNegotiatedContentResult<string>>(actionResult);
Assert.Equal("data: 12", conNegResult.Content);

// if your action was returning data in the body like: Content<string>(HttpStatusCode.Accepted, "some updated data");
actionResult = valuesController.Get(13);
NegotiatedContentResult<string> negResult = Assert.IsType<NegotiatedContentResult<string>>(actionResult);
Assert.Equal(HttpStatusCode.Accepted, negResult.StatusCode);
Assert.Equal("some updated data", negResult.Content);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download