Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a list from an IActionResult

I'm attempting to test the result from an API controller that returns an IActionResult. Currently it is returning an object with status code, value, etc. I'm trying to access just the value.

List<Batch.Context.Models.Batch> newBatch2 = new List<Batch.Context.Models.Batch>();
var actionResultTask = controller.Get();
actionResultTask.Wait();
newBatch2 = actionResultTask.Result as List<Batch.Context.Models.Batch>;

actionResultTask.Result returns a list including a list "Value" which is a list of Batch.Context.Models.Batch and I cannot access this value. It turns to null after casting it to a list.

This is the controller

[HttpGet]
[ProducesResponseType(404)]
[ProducesResponseType(200, Type = typeof(IEnumerable<Batch.Context.Models.Batch>))]
[Route("Batches")]
public async Task<IActionResult> Get()
{
    var myTask = Task.Run(() => utility.GetAllBatches());
    List<Context.Models.Batch> result = await myTask;

    return Ok(result);

}

How do I access the value as a list.

like image 525
user3513071 Avatar asked Jun 12 '18 16:06

user3513071


People also ask

Should I return IActionResult or ActionResult?

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

What does OkObjectResult return?

If using the Ok method with the parameter (an object), it will return an OkObjectResult object. The difference between OkResult and OkObjectResult as the document and Bruce-SqlWork said, the OkResult will show an empty 200 response, and the OkObjectResult will show the 200 responses with the passed object.

How do I use IActionResult in Web API?

IActionResult Return Type in ASP.NET Core Web API: The IActionResult is an interface and it is used to return multiple types of data. For example, if you want to return NotFound, OK, Redirect, etc. data from your action method then you need to use IActionResult as the return type from your action method.


1 Answers

That is because the Result of the Task is an IActionResult derived class, OkObjectResult

Make the test async. Await the Method under test. Then perform the desired assertions.

For example

public async Task MyTest {

    //Arrange
    //...assume controller and dependencies defined.

    //Act
    IActionResult actionResult = await controller.Get();

    //Assert
    var okResult = actionResult as OkObjectResult;
    Assert.IsNotNull(okResult);

    var newBatch = okResult.Value as List<Batch.Context.Models.Batch>;
    Assert.IsNotNull(newBatch);

    //...other assertions.
}
like image 87
Nkosi Avatar answered Nov 15 '22 05:11

Nkosi