将 ActionResult 而不是 IActionResult 转换为 OKObjectResult 以测试 200 状态代码?
我正在转向使用 and ActionResult 而不是 IActionResult,以便 Swagger 自动选择我的类型,但我收到一条错误消息,指出我无法将 ActionResult 转换为 OkObjectResult。
如何转换为 OKObjectResult 来测试 200 状态代码?
我的 IActionResult 控制器
[HttpGet]
public async Task<IActionResult<IEnumerable<Listing>>> Get()
{
var listings = await listingService.GetAllListings();
if (listings.Any())
{
return Ok(listings);
}
return NotFound();
}
我的 ActionResult 控制器
[HttpGet]
public async Task<ActionResult<IEnumerable<Listing>>> Get()
{
var listings = await listingService.GetAllListings();
if (listings.Any())
{
return Ok(listings);
}
return NotFound();
}
我的测试
[Fact]
public async Task ShouldReturnA200StatusCode()
{
var res = (OkObjectResult)await sut.Get();
res.StatusCode.Should().Be(200);
}
I am moving to use and ActionResult rather than IActionResult so that Swagger automatically picks up my types, but I am getting an error saying that I cannot cast an ActionResult to an OkObjectResult.
How do I cast to an OKObjectResult for testing a 200 status code?
My IActionResult Controller
[HttpGet]
public async Task<IActionResult<IEnumerable<Listing>>> Get()
{
var listings = await listingService.GetAllListings();
if (listings.Any())
{
return Ok(listings);
}
return NotFound();
}
My ActionResult Controller
[HttpGet]
public async Task<ActionResult<IEnumerable<Listing>>> Get()
{
var listings = await listingService.GetAllListings();
if (listings.Any())
{
return Ok(listings);
}
return NotFound();
}
My Test
[Fact]
public async Task ShouldReturnA200StatusCode()
{
var res = (OkObjectResult)await sut.Get();
res.StatusCode.Should().Be(200);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看我的解决方案,了解如何使用 XUnit 在单元测试中验证 HTTP 状态代码。
Take a look about my solution about how to validate HTTP status code in unit test using XUnit.
您可以这样做:
如果状态代码为 200,您只会获得
OkObjectResult
。对于其他响应代码,您可以执行相同的操作,例如 401:
This is how you can do it:
You will only get an
OkObjectResult
if the status code is 200.For other response codes you can do the same, e.g. for 401:
按照此答案对类似问题的指导,您需要转换
Result
的 < code>.Get() 方法(而不仅仅是.Get()
方法),然后您可以检查 200 OK StatusCode根据上面的注释,我使用了
ObjectResult
类型,目的是不强制 200 状态代码,并使用as
转换。Following the guidance of this answer to a similar question you need to cast the
Result
of the.Get()
method (rather than just the.Get()
method) and then you can check that for the 200 OK StatusCodeFollowing on from the comments above I have used the
ObjectResult
type with the aim to not coerce the 200 status code and have used theas
casting.