我有一个 Web API 方法,它将两个输入作为
string
并返回输出。我已执行以下步骤来使用 xUnit 进行单元测试。
AutoFixure
创建模拟数据。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 = null
或var member = new List<Member>()
,具体取决于您是否期望null
或控制器中的空列表以返回 404
。
这应该有效
result.Should().BeAssignableTo<NotFoundResult>();