在Xuit中测试id是否大于0



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

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

Assert.IsType将返回广播类型。尝试:

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

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

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响应中返回的对象相同,那么您可能需要调整测试以验证模拟服务的期望值:

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

同样,正如@Jonesopolis建议的那样,您应该使用Assert.IsType<T>的返回结果,而不是使用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检查旁边包含了一条消息。这允许测试框架在测试失败时提供更好的反馈。

最新更新