C# 安装程序模拟无法正常工作(返回已执行的存储库方法空值)
我在为添加实体设置模拟时遇到一些问题。如果我想要获取实体/实体,我的模拟设置可以正常工作,但是当我想要创建(添加)时。我为create设置了一个方法,结果返回null p.S AddProductAsync在我看来,这个方法可能不起作用,尽管我在调试中检查过,但是有一个对该方法的调用C# 安装程序模拟无法正常工作(返回已执行的存储库方法空值),c#,unit-testing,asp.net-core,testing,moq,C#,Unit Testing,Asp.net Core,Testing,Moq,我在为添加实体设置模拟时遇到一些问题。如果我想要获取实体/实体,我的模拟设置可以正常工作,但是当我想要创建(添加)时。我为create设置了一个方法,结果返回null p.S AddProductAsync在我看来,这个方法可能不起作用,尽管我在调试中检查过,但是有一个对该方法的调用 public class ProductServiceTests { private Mock<IProductRepository> _productMockRepo = new Mock&
public class ProductServiceTests
{
private Mock<IProductRepository> _productMockRepo = new Mock<IProductRepository>();
private ProductService _sut;
public ProductServiceTests()
{
_sut = new ProductService(_productMockRepo.Object);
}
_sut是我的服务,_productMockRepo是我的模拟存储库
对于测试,我使用NuGet Package“Moq”
谢谢)问题在于期望值被设置为使用一个特定实例
addingProduct
_productMockRepo.Setup(x => x.AddProductAsync(addingProduct))
.ReturnsAsync(addingProduct);
但在执行测试时,它会在被测试的成员中创建另一个实例
var result = await _sut.AddProductAsync(actualProduct);
我只能假设它做了一些类似于在这里所做的事情
var addingProduct = new Product {
Name = actualProduct.Name,
Price = actualProduct.Price,
Category = actualProduct.Category,
Quantity = actualProduct.Quantity
};
因为测试对象(即:ProductService.AddProductAsync(产品产品)
)未显示
因为它不是安装中使用的实际实例,所以默认情况下,mock将返回null
在这种情况下,在设置预期行为的过程中松开参数匹配
//...
_productMockRepo
.Setup(x => x.AddProductAsync(It.IsAny<Product>())) //<-- loosen expected match
.ReturnsAsync((Product p) => p); //<-- return the argument that was passed to the member
//...
/。。。
_产品回购
.Setup(x=>x.AddProductAsync(It.IsAny())//p);//x、 AddProductAsync(It.Is(p=>addingProduct.Name==p.Name&&…),Times.one);
参考资料:AddProductAsync的方法签名是什么样子的?@haldo是代码示例中的产品谢谢!由于某种原因,我绊倒了,没有找到文档。我会知道的。答案是正确的
//...
_productMockRepo
.Setup(x => x.AddProductAsync(It.IsAny<Product>())) //<-- loosen expected match
.ReturnsAsync((Product p) => p); //<-- return the argument that was passed to the member
//...
_productMockRepo.Verify(x => x.AddProductAsync(It.Is<Product>(p => addingProduct.Name == p.Name && ... )), Times.Once);