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.
IHttpActionResult ultimately returns HttpResponseMessage by providing the customization and reusability features to the developer. IHttpActionResult contains ExecuteAsync method to create an instance of HttpResponseMessage asynchronously. We have to add some code logic in the implemented class as per our requirement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With