如何使用xUNit在WebAPI中测试NotFound



我有一个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());

}
}```

您的问题来自var member = fixture.Create<List<Member>>();

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

相关内容

  • 没有找到相关文章

最新更新