Moq 无法识别未接收依赖项中所需对象的方法的设置

Moq does not recognize the Setup for a method that does not receive the object needed in the dependency

我现在正在使用最小起订量。我有一个案例,我不确定我做错了什么,我希望你能指导我。

代码和测试是:

public class MyLogic{
    private readonly IRepository _repository;

    public MyLogic(IRepository repository)
    {
        _repository = repository;
    }
    public async Task<Product> Create(Estimate estimate, Policy policy)
    {
        Product product = new Product(policy.Title, estimate.Id);
        return await _repository.Create(product);
    }
}

[Fact]
public Class MyLogicTest{
    Mock<IRepository> _repository = new DBRepository();
    MyLogic myLogic =  new MyLogic(_repository);

    Estimate _estimate = new Estimate(){
        Id = Guid.Parse("5aa4d4a1-23e4-495b-b990-08da0d38e5df")
    };

    Policy _policy = new Policy(){
        Title = "The Title"
    };

    public async Task CreateShouldBeDifferentFromNull(){
        Product product = new Product()
        {
            Title = "The Title",
            Id = Guid.Parse("5aa4d4a1-23e4-495b-b990-08da0d38e5df")               
        };

        _repository.Setup(g => g.Create(product)).ReturnsAsync(() => product);
        Product createdProduct = await myLogic.Create(_estimate, _policy);

        Assert.NotNull(createdProduct);
        Assert.Equal(product.Id, createdProduct.Id);

        _repository.Verify(g => g.Create(product));
    }
}

A​​ssert 总是失败,因为 createdProduct 总是 null。而且,我知道我可以更改 class MyLogic 以接收 Product 而不是两个参数。但我想要的是按原样测试代码。

如何让模拟的 IRepository 使用我在测试中声明的 Product 实例,以便测试成功?

您需要将 Create 方法设置为 return 您想要的 Product 当它接收到具有某些特定 Title 类型 Product 的实例时和一些具体的 Id。现在您正在将 Create 方法设置为 return 您想要的 Product 当它接收到您创建的对象时。哪一个当然失败了,因为它与在 Create 方法中创建的对象完全不同。 因此,将您的设置行更改为: _productRepository.Setup(g => g.Create(It.Is<Product>(p => p.Id == product.Id && p.Title == product.Title)).ReturnsAsync(() => product); 或者,您可以覆盖 Equals 方法和 == 运算符,您的原始代码也可以正常工作。