【发布时间】:2022-09-27 21:53:56
【问题描述】:
我有一个模拟的执行器,它根据我们给参数的值在 x 次回调后断言单元。这是我的单元测试的示例代码
[Test]
[TestCase(\"foo\", false, 2)]
[TestCase(\"foo\", true, 3)]
public void CommandLineShouldBeValidTest(string parameter1, bool parameter2, int finalCallbackCounter)
{
int initialCallbackCounter = 0;
var executorMock = new Mock<ITaskExecutor>();
executorMock.Setup(m => m.Execute(It.IsAny<IExecutionContext>(), It.IsAny<ITask>())).Callback<IExecutionContext, ITask>((c, it) =>
{
var p = (ProcessTask)it;
initialCallbackCounter++;
if (initialCallbackCounter == finalCallbackCounter)
{
Assert.AreEqual(expectedCommandLine, p.CommandLine);
}
});
var macro = new Macro(parameter1, parameter2, mock.Object);
macro.Execute();
}
目前我正在使用 finalCallbackCounter 参数,因此例如,如果我将第二个布尔参数设为 true 而不是 false,我需要将其更改为 3(我实际上在当前代码中有更多参数和案例,我只是出于问题的目的对其进行了简化)。
这种方式感觉真的很笨拙,而且不是很有未来感。这个问题有更优雅的解决方案吗?
-
您是否尝试过使用
SetupSequence而不是Setup? -
看这里的例子,我不明白它会有什么帮助? github.com/Moq/moq4/wiki/Quickstart#miscellaneous 除非有办法使用我不知道的 Returns() 重写我的测试
标签: c# .net unit-testing callback moq