如何使用 xUNit 测试 WebAPI 中的 NotFound

问题描述 投票:0回答:2

我有一个 Web API 方法,它将两个输入作为

string
并返回输出。我已执行以下步骤来使用 xUnit 进行单元测试。

  1. 创建了 xUnit 项目并向其添加了一种方法。
  2. 使用
    AutoFixure
    创建模拟数据。
  3. 添加了测试代码并运行测试无需运行API项目。我就在这里做这个吗?我还需要运行 API 项目吗?
  4. 我的测试给出的是结果而不是 NoDataFound。当我从 Postman 运行测试用例时,我得到了预期的结果
    404 error
    但在 xUnit 中,得到了计数为 3 的对象。

我不知道我在哪里缺少什么。请提供任何帮助。 TIA。 下面是我的代码。

public class ControllerTest
{
    private readonly IFixture fixure;
    private readonly Mock<ICustomerService> service;;
    private readonly CustController  controller;

    public CustControllerTest()
    {
        service = new Mock<ICustomerService>();
        controller = new CustController(service.Object);
        fixure = new Fixture();
    }

    [Fact]
    public async Task GetMember_WithZeroAsInput_ShouldReturnNotFound()

    {

        //arrange
            var member = fixure.Create<List<Member>>();//creating a mock for Member object
            var Id = Convert.ToString(0); //0 as input
            var name = Convert.ToString(0);//0 as input

            service.Setup(x => x.GetMember(Id, name)).ReturnsAsync(member);//here I am getting 3 record count even my both inputs are 0

            //act
            var result = await CustController.GetMember(Id, name);//here also I am getting 3 record count even my both inputs are 0.
                //when I am calling GetMember from Postman with 0 as inputs I am getting NotFound result. 

            //assert
            result.Should().NotBeNull();
            result.Result.Should().BeAssignableTo<NotFoundObjectResult>();//getting error here as - Expected memberFlagResult.Result to be assignable to Microsoft.AspNetCore.Mvc.NotFoundObjectResult, but Microsoft.AspNetCore.Mvc.OkObjectResult is not.
            result.Verify(x => x.GetMember(memberId, flagName), Times.Once());
        
    }
}```
.net unit-testing asp.net-web-api xunit autofixture
2个回答
0
投票

您的问题来自线路

var member = fixture.Create<List<Member>>();

fixture.Create
将生成一个匿名对象(https://github.com/AutoFixture/AutoFixture#overview)来解决您的问题,您应该更明确=>
var member = null
var member = new List<Member>()
,具体取决于您是否期望
null
或控制器中的空列表以返回
404


0
投票

这应该有效

result.Should().BeAssignableTo<NotFoundResult>();
© www.soinside.com 2019 - 2024. All rights reserved.