首页 > 解决方案 > 在 Xunit 中测试 id 是否大于 0

问题描述

谁能帮我为以下单元测试编写第二个断言?实际上我想测试 CategoryId 是否大于 0 并且我想使用我的响应数据(CategoryId 由于 Identity 列而在这里自动生成)

 [Fact]
 public async Task PostValidObjectReturnsOkResult()
 {
     //Arrange
     Mock <ICategoryService> m = new Mock <ICategoryService>();
           
     CategoryDTO myData = new CategoryDTO()
     {
          CategoryName = "Items" 
     };

     m.Setup(repo => repo.CreateCategory(myData));

     CategoryController c = new CategoryController(m.Object);

     //Act
     ActionResult response = await c.Post(myData);//response data
        
     //Assert
     Assert.IsType <OkObjectResult>(response);
}

我尝试了以下方法,但没有奏效:

Assert.NotEqual(0,(response.Value as CategoryDTO).CategoryId);
Assert.True(((response.Value as CategoryDTO).CategoryId) > 0);

标签: c#asp.netunit-testingasp.net-web-apixunit

解决方案


我终于像这样修复它:

var okResult = Assert.IsType<OkObjectResult>(response);
Assert.NotEqual(0, (okResult.Value as CategoryDTO).CategoryId);

我还更改了这行代码:

m.Setup(repo => repo.CreateCategory(myData));

到以下代码,因为我们需要指定 Returns() 以便为 CategoryId 提供一些随机数

m.Setup(i => i.CreateCategory(It.IsAny<CategoryDTO>())).Returns(() => Task.FromResult(myData));

推荐阅读