nin*_*der 1 c# ienumerable nsubstitute argument-matching
我正在为一个项目进行单元测试,但我无法弄清楚如何让 NSubstitute 按照我期望的方式工作。我遇到的问题是我要替换的代码在 while 循环中,并且根据替换值返回的内容确定循环是否继续。
我想做的是让 Process() 根据传入的内容返回不同的结果。我试过了
api.Process(Arg.Is<IEnumerable<int>>(new[] {1,2,3}, Arg.Any<bool>()).Returns(new ProcessingResult(){Success = true, IdsNotProcessed = List<int>{30}});
Run Code Online (Sandbox Code Playgroud)
但它似乎不起作用,因为 processingResult 返回 null 因为 NSubstitue 与参数不匹配。
[Test]
public void TestTwoLoops()
{
var api = Substitute.For<IApi>();
api.Process(/*list containing 1,2,3*/, Arg.Any<bool>()).Returns(new ProcessingResult(){Success = true, IdsNotProcessed = List<int>{30}});
api.Process(/*list containing 30*/, Arg.Any<bool>()).Returns(new List<int>{});
var sut = new WidgetMaker(api);
sut.MakeWidget();
}
public class WidgetMaker
{
public WidgetMaker(IApi api)
{
_api = api;
}
public void MakeWidgets(IEnumerable<int> widgetIds)
{
var idsToProcess = widgetIds.ToList();
while(true)
{
if(!idsToProcess.Any())
{
berak;
}
var processingResult = _api.Process(idsToProcess, false);
if(processingResult.Success)
{
idsToProcess.Clear();
idsToProcess.AddRange(processingResult.IdsNotProcessed);
}
else
{
break;
}
}
}
private IApi _api;
}
Run Code Online (Sandbox Code Playgroud)
在我写这个问题的时候,答案就出现了,但我觉得其他人可能会觉得这很有帮助。
使用接受谓词的重载并使用带有 new[] 参数的 SequenceEqualExtension 方法 {/我想要输入的值/}
api.Process(Arg.Is<IEnumerable<int>>(x => x.SequenceEqual(new[] {1,2,3}, Arg.Any<bool>())).Returns(new ProcessingResult(){Success = true, IdsNotProcessed = List<int>{30}});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1096 次 |
| 最近记录: |