Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock an IEnumerable<T> so that I can test a method that receives it

I have a method that I want to test which expects an IEnumerable<T> as a parameter.

I'm currently mocking the contents of the IEnumerable<T> as follows (Using Moq):

 var mockParent = new Mock<ICsvTreeGridExportable>();
 var mockChild = new Mock<ICsvTreeGridExportable>();

How do it put these mocked objects inside an IEnumerable<T> so that I can pass them as a parameter to the method I want to test?

The method I'm testing expects to receive an IEnumerable<ICsvTreeGridExportable>

like image 413
Jamie Dixon Avatar asked Nov 13 '09 12:11

Jamie Dixon


2 Answers

I would just create an array using the collection intialiser syntax. i.e.

var mockParent = new Mock<ICsvTreeGridExportable>();
var mockChild = new Mock<ICsvTreeGridExportable>();

TestMethod(new[] { mockParent.Object, mockChild.Object });

Arrays in .NET implement the IEnumerable<T> interface, so you're all set.

Note: If you want a "pure" IEnumerable<T> (as Luke points out), you could use a little bit of LINQ to do that:

TestMethod((new[] { mockParent.Object, mockChild.Object }).TakeWhile(true));
like image 101
Noldorin Avatar answered Sep 22 '22 11:09

Noldorin


You could just create an array. (Arrays implement the IEnumerable<T> interface.)

var mockEnumerable = new[] { mockParent.Object, mockChild.Object };

If you want a "pure" IEnumerable<T> that can't be cast back to an array etc, then you could create it using a helper method:

var mockEnumerable = CreateEnumerable(mockParent.Object, mockChild.Object);

// ...

public static IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
    foreach (T item in items)
    {
        yield return item;
    }
}

(As Jamie mentions in the comments, you need to use the mocked objects, not the Mock objects. For example, mockParent.Object, mockChild.Object etc, not just mockParent or mockChild.)

like image 43
LukeH Avatar answered Sep 21 '22 11:09

LukeH