【问题标题】:Test if id is greater than 0 in Xunit在 Xunit 中测试 id 是否大于 0
【发布时间】:2021-01-19 05:48:35
【问题描述】:

谁能帮我为以下单元测试编写第二个断言?实际上我想测试 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);

【问题讨论】:

  • 请提供任何可能发生的错误详情。
  • 错误提示:“ActionResult”不包含值的定义

标签: c# asp.net unit-testing asp.net-web-api xunit


【解决方案1】:

我终于把它修好了:

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));

【讨论】:

    【解决方案2】:

    Assert.IsType 将返回转换后的类型。试试:

    var okResult = Assert.IsType<OkObjectResult>(response);
    
    Assert.True(okResult.Value.CategoryId > 0);
    

    【讨论】:

    • 感谢您的回答,但我收到 CategoryId 的错误,这里显示“对象没有 CategoryId 的定义”
    【解决方案3】:

    看起来您要测试的是将值从 ICategoryService 分配回 CategoryDTO 对象的行为。在这种情况下,ICategoryService 的模拟实现需要提供与具体实现相同的结果。看起来您正在使用 Moq,为了实施检查,您可以 use a callback 检查以下内容:

    var expectedCategoryId = 42;
    m.Setup(repo => repo.CreateCategory(myData))
     .Callback(() => myData.CategoryId = expectedCategoryId);
    
    // The rest of the testing code
    
    Assert.Equal(expectedCategoryId, resultValue.CategoryId);
    

    如果传递给服务的对象与控制器的 OK 响应中返回的对象相同,那么您可能需要将测试调整为 verify the expectations of the mock service

    // The rest of the testing code
    
    m.VerifyAll();
    

    正如@Jonesopolis 建议的那样,您应该使用Assert.IsType&lt;T&gt; 的返回结果,而不是使用as 运算符来转换类型。通过稍微调整他们的代码,这应该会简化您的测试逻辑应该是什么样子:

    // The rest of the testing code
    
    var okObjectResult = Assert.IsType<OkObjectResult>(response);
    var resultValue = Assert.IsType<CategoryDTO>(okObjectResult);
    Assert.True(resultValue.CategoryId > 0, "Result value does not have CategoryId assigned");
    

    另外请注意,我在Assert.True 检查旁边包含了一条消息。这允许测试框架在测试失败时提供更好的反馈。

    【讨论】:

    • 感谢您的回答我正在我的代码中尝试您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2017-08-15
    • 2018-05-16
    • 2017-02-28
    • 2019-05-21
    • 1970-01-01
    相关资源
    最近更新 更多