开发者

Mock object returning a list of mocks with Moq

开发者 https://www.devze.com 2022-12-17 23:08 出处:网络
I am trying to test the following code 开发者_如何学运维public void CleanUp() { List<ITask> tasks = _cleanupTaskFactory.GetTasks();

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
    }

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.

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?


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());

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());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号