我有一个如下所示的方法,我正在为此尝试编写单元测试。
public IActionResult Get(string market, string program, string destination, string language, string type, string subtype) {
var salesItemTypeNumber = (int)Enum.Parse(typeof(SalesItemType), type);
var salesItemRequest = new SalesItemRequest {
Market = market,
Program = program,
Destination = destination,
Type = salesItemTypeNumber,
Language = language
};
var loggingFields = logger.GetLoggingFields(salesItemRequest);
var salesItems = new List<SalesItem>();
try {
salesItems = repository.GetSalesItems(salesItemRequest).ToList();
if (salesItems == null || !salesItems.Any()) {
return StatusCode(StatusCodes.Status204NoContent);
}
var listOfSalesItems = salesItems.Select(salesItem => new {
Sku = salesItem.Sku,
Code = salesItem.Code,
Description = salesItem.Description,
EnglishDescription = salesItem.EnglishDescription
}).ToList();
return StatusCode(StatusCodes.Status200OK, listOfSalesItems);
}
}
我必须模拟GetSalesItems()方法。当我为该方法设置时,它不会为我运行特定代码段返回期望值。请在下面找到单元测试方法。指导我怎么了。
[TestMethod]
public void Check_Status_When_Get_Method_Is_Invoked() {
var salesItemsList = new List<SalesItem> {
new SalesItem {
Sku = "BB-GB-LON",
Code = "BB",
Description = "Breakfast",
EnglishDescription = "Breakfast"
},
new SalesItem {
Sku = "COL1-GB-LON",
Code = "COL1",
Description = "Course Literature 1-6 weeks",
EnglishDescription = "Course Literature 1-6 weeks"
},
};
priceRepositoryMock.Setup(m => m.GetSalesItems(new SalesItemRequest() {
Market = "DEB",
Program = "ILS",
Destination = "GB-LON",
Language = "en"
})).Returns(salesItemsList);
var response = salesItemController.Get("DEB", "ILS", "GB-LON", "en", "80", string.Empty);
Assert.AreEqual(200, ((ObjectResult) response).StatusCode);
}
答案 0 :(得分:1)
设置中使用的参数与被测方法中的参数不同。您可以使用
之类的参数匹配器 It.Is<T>()
priceRepositoryMock
.Setup(_ => _.GetSalesItems(It.Is<SalesItemRequest>(
arg => arg.Market == "DEB" &&
arg.Program == "ILS" &&
arg.Destination == "GB-LON"
&& arg.Language == "en"
))
.Returns(salesItemsList);
或
It.IsAny<T>()
priceRepositoryMock
.Setup(_ => _.GetSalesItems(It.IsAny<SalesItemRequest>()))
.Returns(salesItemsList);
匹配传递到模拟中的参数,以便在执行测试时被调用时表现出预期的效果。
参考Moq Quickstart可以更好地理解如何在模拟框架中使用参数匹配器。