我現在正在使用起訂量。我有一個案例,我不確定自己做錯了什么,希望您能指導我。
代碼和測驗是:
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));
}
}
斷言總是失敗,因為 createdProduct 總是為空。而且,我知道我可以更改 MyLogic 類以接收 Product 而不是兩個引數。但我想要的是按原樣測驗代碼。
如何使模擬的 IRepository 使用我在測驗中宣告的 Product 實體以使測驗成功?
uj5u.com熱心網友回復:
您需要設定該方法以在它接收到具有某些特定和某些特定的型別的實體時Create回傳您想要的。現在,您正在設定方法以在準確接收到您創建的物件時回傳您想要的。這當然會失敗,因為這與在您的方法中創建的物件完全不同。因此,將您的設定行更改為:
或者,您可以覆寫 Equals 方法和 == 運算子,您的原始代碼也可以正常作業。ProductProductTitleIdCreateProductCreate_productRepository.Setup(g => g.Create(It.Is<Product>(p => p.Id == product.Id && p.Title == product.Title)).ReturnsAsync(() => product);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449501.html
