【问题标题】:How to extract a list from an IActionResult如何从 IActionResult 中提取列表
【发布时间】:2018-06-12 16:15:42
【问题描述】:

我正在尝试从返回 IActionResult 的 API 控制器测试结果。目前它正在返回一个带有状态码、值等的对象。我正在尝试仅访问该值。

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

这是控制器

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

}

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

【问题讨论】:

  • 我没有用 .net core 做过这个,但我想与 webapi2 类似,接口IActionResult 是您返回的数据的包装器。所以它是一个包含相关标题、状态代码和内容的对象。在 webapi2 中,您将反序列化 response.Content。

标签: c# unit-testing asp.net-core asp.net-core-webapi


【解决方案1】:

那是因为TaskResultIActionResult派生类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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多