gpt4 book ai didi

c# - 如何从 IActionResult 中提取列表

转载 作者:太空狗 更新时间:2023-10-30 01:13:13 27 4
gpt4 key购买 nike

我正在尝试测试返回 IActionResult 的 API Controller 的结果。目前它正在返回一个包含状态代码、值等的对象。我正在尝试仅访问该值。

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

这是 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);

}

如何访问列表中的值。

最佳答案

那是因为TaskResult是一个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.
}

关于c# - 如何从 IActionResult 中提取列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com