Mock returns mocks list 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 } 

In my test, I create a mocked implementation of _cleanupTaskFactory, and I want to drown out the GetTasks () method to return a type:

 List<Mock<ITask>> 

... but the compiler will not accept this as a return value.

My goal is to ensure that every task returned has a .Execute () method called using the Verify () MoQ method.

How can I claim that every task is completed?

+7
unit-testing moq mocking
source share
1 answer

In the _cleanUpTaskFactory wizard _cleanUpTaskFactory you can 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 you keep the link to the mocks list, and when you are done testing, you mocks over all the layouts and call Verify() as follows:

 mocks.ForEach(m => m.Verify()); 
+10
source share