How to test response StatusCode of MVC Controller Action

Viewed 9448

I want to write unit test for my controller.

I want to check the response codes of actions. For example, Post action should return 201, get should return 200, etc.

However, the Action method return IActionResult. How do I get response code from the ActionResult?

 //setup
 MyController controller = CreateController<MyController>();

 //action
 var actionResult = controller.Post(dafXml);

 //assert
 ???

I don't want to check the type of action result since I care only about the status code. for example, 201 can be achieved by CreatedAtAction, CreatedAtRoute or with custom ObjectResult...

2 Answers

FluentAssertions provide an elegant way to assert controller response codes. See examples below.

// 200
actionResult.Should().BeOfType<OkObjectResult>()
    .Which.StatusCode.Should().Be((int)HttpStatusCode.OK);

// 201
actionResult.Should().BeOfType<CreatedResult>()
    .Which.StatusCode.Should().Be((int)HttpStatusCode.Created);

// 500
actionResult.Should().BeOfType<ObjectResult>()
    .Which.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError);

You can simply call ExecuteAsync method over IHttpActionResult object to get Http response of type HttpResponseMessage and then access StatusCode property to verify it.

You can also refer to these docs to know how IHttpActionResult works.

Related