c# - 在 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);
解决方案
我终于像这样修复它:
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));
推荐阅读
- node.js - Lambda 上的 GraphQL 查询在突变后没有返回一致的数据(起初)
- java - Java ConditionFactory 在条件满足后等待 pollingTime
- java - Google InApp Billing - 从 onSkuDetailsResponse 获得的 skuDetailsList 的标题绑定到列表视图控件
- node.js - 无法通过 jenkins 作业中的“npm install cypress”安装 cypress
- python - 如何向当前登录的用户 Django 发送电子邮件
- python - 如何在不存在的值上使用 if else
- java - 为什么 BigDecimal("20") 不等于 BigDecimal("2E+1")
- python - 如何优化python中的for循环?
- python - 美丽的汤不会从“下一页”中抓取数据
- python - keras - 1D-CNN 输入兼容性错误,时间序列问题