单元测试 AspNetCore 控制器检查 HttpStatusCode 与 ActionResult<T> 结果
Posted
技术标签:
【中文标题】单元测试 AspNetCore 控制器检查 HttpStatusCode 与 ActionResult<T> 结果【英文标题】:Unit test AspNetCore Controller check HttpStatusCode with ActionResult<T> result 【发布时间】:2020-03-10 08:43:49 【问题描述】:我正在尝试从对控制器的调用中检查 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”。
关于如何实现这一点的任何想法?
【问题讨论】:
【参考方案1】:假设被测方法返回了示例代码所暗示的错误请求,这将类似于
//...
if(...)
return BadRequest();
//...
那么在单元测试的时候,需要从action result中提取包装出来的结果
//Arrange
//...omitted for brevity
//Act
ActionResult<PagedResult<PersoDemandLiteResponse>> response =
await controller.GetDemandsByFilterAsync(request);
//Assert
BadRequestResult actual = response.Result as BadRequestResult;
Assert.NotNull(actual);
int badRequest = (int)HttpStatusCode.BadRequest;
Assert.Equal(badRequest, actual.StatusCode);
参考Controller action return types in ASP.NET Core Web API
【讨论】:
太好了,我不知道如何像这样使用它,是的,该方法返回了一个错误的请求。以上是关于单元测试 AspNetCore 控制器检查 HttpStatusCode 与 ActionResult<T> 结果的主要内容,如果未能解决你的问题,请参考以下文章
在 ASP.NET Core MVC API 控制器上对 AuthorizeAttribute 进行单元测试
AspNetCore 集成测试多个 WebApplicationFactory 实例?