简体   繁体   English

基于使用Moq在单元测试中传递的参数返回不同的模拟值

[英]Returning different mocked values based on parameters passed in Unit Test with Moq

I have a method called GetTasks() that returns 10 tasks objects. 我有一个名为GetTasks()的方法,它返回10个任务对象。 I want to moq this task for unit testing purposes. 我想将此任务用于单元测试目的。 Here is the code: 这是代码:

 _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}}

});

This works fine, but there is something missing. 这很好,但有些东西缺失。 Filtering on Task severity would not work here. 过滤任务严重性在此处不起作用。

My question is, how do I setup Moq so that if the list of Severity passed in has a High Severity within, it will return 3 instead of 10 tasks? 我的问题是,我如何设置Moq,以便如果传入的严重性列表具有高严重性,它将返回3而不是10个任务? So in other words, if I pass it: 换句话说,如果我通过它:

// Arrange
var severities = new List<Severity>() { Severity.High };

I want to return 3 tasks instead of 10. 我想要返回3个任务而不是10个。

Returns not only accepts a value but you can also pass a delegate with an exact signature as your method and actual parameters will be passed to the delegate. Returns不仅接受一个值,而且还可以传递具有精确签名的委托作为方法,并且实际参数将传递给委托。 Then, you can do whatever you want with these parameters. 然后,您可以使用这些参数执行任何操作。 In your case 在你的情况下

 .Returns( (int i, List<Stage> stages, List<Severity> severities) =>
          {
              if ( severities.Contains(...) 
                 return ...
              else
                 ...
          } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM