Patrick
Patrick

Reputation: 5836

Unit Testing IHttpActionResult Controller - Testing for 200 OK fails

This is probably a fairly simple question but I'll admit, I'm stuck.

I have a controller that is returning IHttpActionResult and I need to write unit tests for this.

Here's the controller:

public IHttpActionResult GetPerson(int id) {

    Person person = repository.Get(id);

    if (person == null) {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }

    return Ok(new {
        User = person
    });

}

Here's the unit test:

[TestMethod]
public void GetReturnsValidPerson() {

    var userController = new UserController();

    IHttpActionResult actionResult = userController.GetPerson(1);

    Assert.IsInstanceOfType(actionResult, typeof(OkResult));

}

And here's the error from the test:

Assert.IsInstanceOfType failed. Expected type:System.Web.Http.Results.OkResult Actual type: System.Web.Http.Results.OkNegotiatedContentResult1[<>f__AnonymousType11[DataAccess.BO.Person]]

What exactly is going on here? The return from the controller is an HTTP 200 Ok response. Why is this expecting OkNegotiatedContentResult?

Upvotes: 2

Views: 6406

Answers (1)

Tah
Tah

Reputation: 1536

Per the Asp.Net documentation, the result of an IHttpActionResult is OkNegotiatedContentResult. Your Assert comparison should check for that.

Unit Testing Controllers in Asp.Net

Action returns 200 (OK) with a response body

The Get method calls Ok(product) if the product is found. In the unit test, make sure the return type is OkNegotiatedContentResult and the returned product has the right ID.

Upvotes: 3

Related Questions