当结果在IActionResult类型中返回时,如何在Xunit中获取内容值

我有一个使用Xunit的unit testing项目,我们测试的方法返回IActionResult

我看到有些人建议使用“NegotiatedContentResult”来获取IActionResult的内容,但这在Xunit中不起作用。

所以我想知道如何在IActionResult中获取IActionResult的内容值?

测试代码示例如下:

 public void GetTest() { var getTest = new ResourcesController(mockDb); var result = getTest.Get("1"); //Here I want to convert the result to my model called Resource and //compare the attribute Description like below. Resource r = ?? //to get the content value of the IActionResult Assert.Equal("test", r.Description); } 

有没有人知道如何在XUnit中这样做?

取决于您期望返回的内容。 从前面的示例中,您使用了这样的操作。

 [HttpGet("{id}")] public IActionResult Get(string id) { var r = unitOfWork.Resources.Get(id); unitOfWork.Complete(); Models.Resource result = ConvertResourceFromCoreToApi(r); if (result == null) { return NotFound(); } else { return Ok(result); } } 

该方法将返回OkObjectResultNotFoundResult 。 如果测试方法的期望是它返回Ok()那么你需要将测试中的结果转换为你期望的,然后对你的断言进行断言

 public void GetTest_Given_Id_Should_Return_OkObjectResult_With_Resource() { //Arrange var expected = "test"; var controller = new ResourcesController(mockDb); //Act var actionResult = controller.Get("1"); //Assert var okObjectResult = actionResult as OkObjectResult; Assert.NotNull(okObjectResult); var model = okObjectResult.Value as Models.Resource; Assert.NotNull(model); var actual = model.Description; Assert.Equal(expected, actual); }