我正在嘗試測試返回IActionResult. 目前它正在返回一個帶有狀態(tài)代碼、值等的對象。我試圖只訪問該值。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我無法訪問此值。將其轉(zhuǎn)換為列表后,它變?yōu)閚ull。這是控制器[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);}如何以列表形式訪問該值。
1 回答

達(dá)令說
TA貢獻(xiàn)1821條經(jīng)驗 獲得超6個贊
這是因為Result的Task是一個IActionResult派生類,OkObjectResult
使測試異步。等待被測方法。然后執(zhí)行所需的斷言。
例如
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.
}
- 1 回答
- 0 關(guān)注
- 460 瀏覽
添加回答
舉報
0/150
提交
取消