我有一个名为 MyService 的服务,它实现了 IService,我的 AppContext(继承自 DbContext)被注入到该服务中。它有一个名为
AddProduct(ProductDTO)
的方法,它只返回一个任务,因为它只是一个插入。我在此方法中将输入参数 ProductDTO 映射到 Product 实体,并在此方法中调用 _appContext.AddAsync(mappedentity)
和 _appcontext.SaveChangesAsync()
。
现在,我已经在 NSubstitute 中编写了一个单元测试用例,通过在我的服务中调用上述方法来添加产品。尽管点击此服务方法的主应用程序工作正常并且正在创建产品,但此测试用例仍然失败,并显示错误“预计仅收到一个呼叫。但没有收到任何呼叫”。
这是测试用例代码。我不确定为什么在收到的第一个断言时失败。我尝试了
Add()
和 AddAsync()
以及 SaveChanges
()。
public class MyServiceTests
{
[Fact]
public async Task AddProduct_ShouldAddProductToContext()
{
// Arrange
var appContext = Substitute.For<IAppContext>();
var myService = new MyService(appContext);
var productDTO = new ProductDTO
{
// Initialize properties for the ProductDTO
// ...
};
// Act
await myService.AddProduct(productDTO);
// Assert
await appContext.Received(1).Add(Arg.Any<Product>());
await appContext.Received(1).SaveChanges();
}
}
我犯的错误是在断言中。最后两行需要用此替换。
await appContext.Products.Received(1).AddAsync(Arg.Any<Product>());
await appContext.Received(1).SaveChangesAsync(true);
我在 SaveChanges 上缺少 true,并且没有检查产品数据库集上的 Received。