首页 > 解决方案 > 如何从 IActionResult 中提取列表

问题描述

我正在尝试从返回IActionResult. 目前它正在返回一个带有状态码、值等的对象。我正在尝试仅访问该值。

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返回一个列表,其中包括一个列表“值”,它是一个列表,Batch.Context.Models.Batch我无法访问该值。将其转换为列表后变为空。

这是控制器

[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);

}

如何以列表的形式访问该值。

标签: c#unit-testingasp.net-coreasp.net-core-webapi

解决方案


那是因为 的ResultTask派生IActionResult类,OkObjectResult

使测试异步。等待被测方法。然后执行所需的断言。

例如

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.
}

推荐阅读