List<int>.Contains) 不能用于设置/验证表达式
List<int>.Contains) may not be used in setup / verification expressions
我想要 Mock 一个方法,但我的方法处于 Condition 状态,我需要该值为 true 并且如果我不模拟我的方法,此操作会使我的测试通过,它会给我 null 异常,所以这很重要
这是我的测试
[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
问题
所以如果你看到我需要我的条件有真正的价值,但我不知道我如何在模拟中发送它?
模拟 GetSemesterProductTypeIds()
调用比模拟 Contains()
方法更有意义。
根据您的示例,让 GetSemesterProductTypeIds()
return 您产品的产品类型 ID 使 Contains()
调用结果为真。
_productService
.Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
.Returns(new List<int> { 15 });
我想要 Mock 一个方法,但我的方法处于 Condition 状态,我需要该值为 true 并且如果我不模拟我的方法,此操作会使我的测试通过,它会给我 null 异常,所以这很重要 这是我的测试
[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
问题 所以如果你看到我需要我的条件有真正的价值,但我不知道我如何在模拟中发送它?
模拟 GetSemesterProductTypeIds()
调用比模拟 Contains()
方法更有意义。
根据您的示例,让 GetSemesterProductTypeIds()
return 您产品的产品类型 ID 使 Contains()
调用结果为真。
_productService
.Setup(x => x.GetSemesterProductTypeIds(It.IsAny<int[]>())
.Returns(new List<int> { 15 });