模拟对象返回带有Moq的模拟列表 [英] Mock object returning a list of mocks with Moq
问题描述
我正在尝试测试以下代码
I am trying to test the following code
public void CleanUp()
{
List<ITask> tasks = _cleanupTaskFactory.GetTasks();
//Make sure each task has the task.Execute() method called on them
}
在测试中,我创建了_cleanupTaskFactory的模拟实现,并且想对GetTasks()方法存根以返回类型:
In my test I create a mocked implementation of _cleanupTaskFactory, and I want to stub the GetTasks() method to return a type:
List<Mock<ITask>>
...但是编译器不会接受它作为返回值.
...but the compiler won't accept that as a return value.
我的目标是确保每个返回的任务都具有使用Verify()MoQ方法调用的.Execute()方法.
My goal is to ensure that each task returned has the .Execute() method called on it using the Verify() MoQ method.
我如何断言每个任务都已执行?
How can I assert that each task gets executed?
推荐答案
在您的_cleanUpTaskFactory
模拟中,您可以简单地执行以下操作:
In your _cleanUpTaskFactory
mock you could simply do something like the following:
var mocks = new List<Mock<ITask>>();
for(var i = 0; i < 10; i++){
var mock = new Mock<ITask>();
mock.Setup(t => t.Execute()).Verifiable();
mocks.Add(mock);
}
_cleanUpTaskFactoryMock.Setup(f => f.GetTasks()).Returns(mocks.Select(m => m.Object).Tolist());
现在请确保保留对mocks
列表的引用,并在完成测试后遍历所有模拟并像下面这样调用Verify()
:
Now make sure to keep a reference to the mocks
list, and when you done with your testing you iterate over all the mocks and call Verify()
like so:
mocks.ForEach(m => m.Verify());
这篇关于模拟对象返回带有Moq的模拟列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!