Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }

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?

like image 230
Steve Horn Avatar asked Jan 26 '10 14:01

Steve Horn


People also ask

What is CallBase in Moq?

CallBase , when initialized during a mock construction, is used to specify whether the base class virtual implementation will be invoked for mocked dependencies if no setup is matched. The default value is false . This is useful when mocking HTML/web controls of the System.

What is the difference between mocking and stubbing?

Mocks verify the behavior of the code you're testing, also known as the system under test. Mocks should be used when you want to test the order in which functions are called. Stubs verify the state of the system under test.

What is callback in Moq?

Callbacks. A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.


1 Answers

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());
like image 154
Klaus Byskov Pedersen Avatar answered Sep 20 '22 16:09

Klaus Byskov Pedersen