25

I'm learning some Web Api basics and I want to return and pass an object by Ok(object). Something like this:

[HttpGet]
public IHttpActionResult Get()
{
    var someString = "";
    return Ok(someString);
}

Now I want to test this method and to assert if the returned string from this Get() method is the same as expected. I Guess will look something like this:

[TestMethod]
public void TestGet()
{
    IHttpActionResult result = controller.Get();
    Assert.AreEqual("", result.??);
}

I saw this question but the best answer is explaining how to validate the HttpStatusCode, not the passed object.

Community
  • 1
  • 1
Stanimir Yakimov
  • 864
  • 3
  • 14
  • 31
  • 2
    Rather than testing that the result is exactly equal to something, what do you care about in the result? – Jon Skeet May 02 '15 at 13:37
  • @JonSkeet You're right. Instead of trying to test if the passing object is valid, I will just insert some postconditions and depending on them, I will return different `HttpActionResults`.Thank you so much. – Stanimir Yakimov May 02 '15 at 13:49
  • actually, there are cases that testing the returned result makes sense. – Khanh TO May 02 '15 at 13:53
  • @KhanhTO Give an example. – Stanimir Yakimov May 02 '15 at 13:56
  • 2
    For example: when you test a factory method, you need to test whether the returned object is of the expected type. There are countless cases where testing returned result makes sense, this is just one example. – Khanh TO May 02 '15 at 13:59

1 Answers1

46

You can access the returned string by casting the result to OkNegotiatedContentResult<string> and accessing its Content property.

[TestMethod]
public void TestGet()
{
    IHttpActionResult actionResult = controller.Get();
    var contentResult = actionResult as OkNegotiatedContentResult<string>;
    Assert.AreEqual("", contentResult.Content);
}

Example code from: http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api

Khanh TO
  • 48,509
  • 13
  • 99
  • 115