我有一个名为GetTasks()
的方法,它返回10个任务对象。我想将此任务用于单元测试目的。这是代码:
_crateRecallService.Setup(m => m.GetTasks(It.IsAny<int>(), It.IsAny<List<Stage>>(), It.IsAny<List<Severity>>())).Returns(new List<CrateRecallTaskWithComms>()
{
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "1", PkCTaskID = 1, CampaignId = 1, Severity = "High"}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "2", PkCTaskID = 2, CampaignId = 2, Severity = "High"}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "3", PkCTaskID = 3, CampaignId = 3, Severity = "High"}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "4", PkCTaskID = 4, CampaignId = 4}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "5", PkCTaskID = 5, CampaignId = 5}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "6", PkCTaskID = 6, CampaignId = 6}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "7", PkCTaskID = 7, CampaignId = 7}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "8", PkCTaskID = 8, CampaignId = 8}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "9", PkCTaskID = 9, CampaignId = 9}},
new CrateRecallTaskWithComms() { CrateRecallTas = new CrateRecallTas() { CrateId = "10", PkCTaskID = 10, CampaignId = 10}}
});
这很好用,但有些东西不见了。过滤任务严重性在此处不起作用。
我的问题是,如何设置Moq,以便在传入的严重性列表中具有高严重性时,它将返回3而不是10个任务?换句话说,如果我通过它:
// Arrange
var severities = new List<Severity>() { Severity.High };
我想要返回3个任务而不是10个。
答案 0 :(得分:15)
Returns
不仅接受一个值,而且还可以传递具有精确签名的委托作为您的方法,并且实际参数将传递给委托。然后,您可以使用这些参数执行任何操作。在你的情况下
.Returns( (int i, List<Stage> stages, List<Severity> severities) =>
{
if ( severities.Contains(...)
return ...
else
...
} );