Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the object from HttpActionResult Ok method (Web Api)? [duplicate]

Tags:

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.

like image 779
Stanimir Yakimov Avatar asked May 02 '15 13:05

Stanimir Yakimov


People also ask

What does IHttpActionResult return?

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.


1 Answers

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

like image 162
Khanh TO Avatar answered Oct 04 '22 19:10

Khanh TO