use*_*071 5 c# unit-testing asp.net-core asp.net-core-webapi
我正在尝试测试返回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>;
Run Code Online (Sandbox Code Playgroud)
actionResultTask.Result返回一个列表,其中包含一个列表“值”,它是一个列表,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);
}
Run Code Online (Sandbox Code Playgroud)
如何以列表形式访问该值。
这是因为Result的Task是一个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.
}
Run Code Online (Sandbox Code Playgroud)