将 ActionResult 而不是 IActionResult 转换为 OKObjectResult 以测试 200 状态代码?

发布于 2025-01-17 02:03:31 字数 1007 浏览 2 评论 0原文

我正在转向使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌路终见情 2025-01-24 02:03:31

看看我的解决方案,了解如何使用 XUnit 在单元测试中验证 HTTP 状态代码。

[Fact]
public async Task UpdateProduct_When_Product_IsValid_ShouldReturn200()
{
    //Arrange
    ProductDto productDto = new DataGenerator()
        .GenerateProductDto_Valid(1)
        .First();

    var result = _productAppServiceMock.Setup(p => p
    .UpdateAsync(
        It.IsAny<Guid>(),
        It.IsAny<ProductDto>()))
    .ReturnsAsync(() => productDto);

    //Act
    var itemHttp = await productController
        .UpdateProductAsync(productDto.Id, productDto);

    //Assert
    _productAppServiceMock.Verify(p => p.UpdateAsync(It.IsAny<Guid>(),
        productDto), times: Times.Once);

    Assert.Equal(typeof(Microsoft.AspNetCore.Mvc.OkObjectResult), itemHttp.GetType());
}

Take a look about my solution about how to validate HTTP status code in unit test using XUnit.

[Fact]
public async Task UpdateProduct_When_Product_IsValid_ShouldReturn200()
{
    //Arrange
    ProductDto productDto = new DataGenerator()
        .GenerateProductDto_Valid(1)
        .First();

    var result = _productAppServiceMock.Setup(p => p
    .UpdateAsync(
        It.IsAny<Guid>(),
        It.IsAny<ProductDto>()))
    .ReturnsAsync(() => productDto);

    //Act
    var itemHttp = await productController
        .UpdateProductAsync(productDto.Id, productDto);

    //Assert
    _productAppServiceMock.Verify(p => p.UpdateAsync(It.IsAny<Guid>(),
        productDto), times: Times.Once);

    Assert.Equal(typeof(Microsoft.AspNetCore.Mvc.OkObjectResult), itemHttp.GetType());
}
北方的韩爷 2025-01-24 02:03:31

您可以这样做:

[Fact]
public async Task ShouldReturnA200StatusCode()
{
    var res = await sut.Get();

    Assert.IsType<OkObjectResult>(res.Result);
}

如果状态代码为 200,您只会获得 OkObjectResult
对于其他响应代码,您可以执行相同的操作,例如 401:

[Fact]
public async Task ShouldReturnA401StatusCode()
{
    var res = await sut.Get();

    Assert.IsType<UnauthorizedResult>(res.Result);
}

This is how you can do it:

[Fact]
public async Task ShouldReturnA200StatusCode()
{
    var res = await sut.Get();

    Assert.IsType<OkObjectResult>(res.Result);
}

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:

[Fact]
public async Task ShouldReturnA401StatusCode()
{
    var res = await sut.Get();

    Assert.IsType<UnauthorizedResult>(res.Result);
}
指尖微凉心微凉 2025-01-24 02:03:31

按照此答案对类似问题的指导,您需要转换 Result 的 < code>.Get() 方法(而不仅仅是 .Get() 方法),然后您可以检查 200 OK StatusCode


    [Fact]
    public async Task ShouldReturnA200StatusCode()
    {
        var res = await sut.Get();

        var okObj = res.Result as ObjectResult;

        okObj.StatusCode.Should().Be(StatusCodes.Status200OK);
    }

根据上面的注释,我使用了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 StatusCode


    [Fact]
    public async Task ShouldReturnA200StatusCode()
    {
        var res = await sut.Get();

        var okObj = res.Result as ObjectResult;

        okObj.StatusCode.Should().Be(StatusCodes.Status200OK);
    }

Following on from the comments above I have used the ObjectResult type with the aim to not coerce the 200 status code and have used the as casting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文