Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking foreach loop with Moq

I want to loop throug a XmlNodeList. How do you mock a XmlNodeList in Moq, so you can loop through it like in a foreach loop:

        foreach (XmlNode xmlNode in nodes)
        {
            //Do something with node
        }

I have tried to set up via a the SetupSequence method, but I haven't been able to create the desired mock.

like image 512
Morten Avatar asked Oct 31 '12 16:10

Morten


1 Answers

The foreach calls GetEnumerator under the hood and that's what you need to mock:

var xmlNodesMock = new Mock<XmlNodeList>();
xmlNodesList
    .Setup(l => l.GetEnumerator())
    .Returns(new XmlNode[] { /* values go here */ }.GetEnumerator());

Naturally you need to initialize XmlNode array in Returns method with actual values. Keep in mind that mocked list has to be injectable to the tested method, so that you can replace actual implementation.

like image 53
k.m Avatar answered Sep 28 '22 18:09

k.m