我正在尝试从对控制器的调用中检查HttpStatusCode,但是我不知道如何将我的ActionResult<T>
转换为HttpStatusCodeResult
。
控制器的方法:
[Get]
public async Task<ActionResult<PagedResult<PersoDemandLiteResponse>>> GetDemandsByFilterAsync([FromQuery] DemandFilterRequest filter)
=> await this.GetAsync(() => DemandService.GetDemandByFilterAsync(filter), (sources) => sources);
这是我的测试方法(简化):
... mocking of the services ...
var controller = new DemandController(demandService, organizationService.Object, productService.Object, Mapper.Object);
var request = new DemandFilterRequest { OrganizationId = Guid.NewGuid() };
var result = await controller.GetDemandsByFilterAsync(request);
//I would like to do something like this
var action = result as HttpStatusCodeResult;
var badRequest = (int)HttpStatusCode.BadRequest;
Assert.Equal(badRequest, action.StatusCode);
但是出现以下错误:
错误CS0039无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将类型“ Microsoft.AspNetCore.Mvc.ActionResult>”转换为“ System.Web.Mvc.HttpStatusCodeResult”。
关于如何实现此目标的任何想法?
答案 0 :(得分:2)
假设示例代码暗示测试中的方法返回了错误的请求,那将类似于
//...
if(...)
return BadRequest();
//...
然后在进行单元测试时,需要从操作结果中提取包装的结果
//Arrange
//...omitted for brevity
//Act
ActionResult<PagedResult<PersoDemandLiteResponse>> response =
await controller.GetDemandsByFilterAsync(request);
//Assert
var actual = response.Result as BadRequestResult;
Assert.NotNull(actual);