我想模擬一個方法,但我的方法在 Condition 中,我需要值為 true,如果我不模擬我的方法,此操作使我的測驗通過,它給我空例外,所以重要的是這是我的測驗
[Test]
public void Can_return_price_according_to_semester_status()
{
var product = new Product
{
ProductTypeId = 15,
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
PreRegistrationPrice = 10.99M
};
_productService.Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
.Contains(product.ProductTypeId)).Returns(true);// this is my target mock
var customer = new Customer();
_priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(product.Price);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(product.PreRegistrationPrice);
}
和 GetFinalPrice :
if (_productService.GetSemesterProductTypeIds().Contains(product.ProductTypeId))// this is target of my mock
{
if (enrollmentTypeId <= 0)
{
if (product.SemesterStatus == SemesterStatus.PreRegistration)
{
enrollmentTypeId = (int)EnrollmentType.PreRegistered;
}
}
if (enrollmentTypeId == (int)EnrollmentType.PreRegistered)
{
price = product.PreRegistrationPrice;
}
}// some operation after this
問題 所以如果你看到我需要我的條件有真正的價值但我不知道我如何在模擬中發送它?
uj5u.com熱心網友回復:
GetSemesterProductTypeIds()模擬呼叫比模擬方法更有意義Contains()。
根據您的示例,讓GetSemesterProductTypeIds()回傳產品的產品型別 ID 以使Contains()呼叫結果為真。
_productService
.Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
.Returns(new List<int> { 15 });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/468145.html
上一篇:在Spock的where塊中使用分配的引數斷言模擬呼叫
下一篇:為屬性裝飾器實作單元測驗
