Moq Validation Fails When SelectMany Selected

I use NUnit, Moq and StructureMap.

I have the following NUnit test:

    [Test]
    public void ShouldCallCustomMethod_ForAllICustomInterfaceMocks()
    {
        var customInterfaceMock1 = new Mock<ICustomInterface>();
        var customInterfaceMock2 = new Mock<ICustomInterface>();

        ObjectFactory.Inject(customInterfaceMock1.Object);
        ObjectFactory.Inject(customInterfaceMock2.Object);

        var sut = new SUT();
        sut.MethodThatShouldCallCustomMethodOnMocks();

        customInterfaceMock1.Verify(m => m.CustomMethod());
        customInterfaceMock2.Verify(m => m.CustomMethod());
    }

ICustomInterface:

public interface ICustomInterface
{
    IEnumerable<Type> CustomMethod();
}

Now, if the implementation of the SUT class is as follows:

public class SUT
{
    public IEnumerable<Type> MethodThatShouldCallCustomMethodOnMocks()
    {
        var result = ObjectFactory.GetAllInstances<ICustomInterface>()
             .SelectMany(i => i.CustomMethod());


        return result;
    }
}

the test from above is not executed because the CustomMethod method is not called in mocks. However, if I changed the implementation of the SUT class to this:

public class SUT
{
    public IEnumerable<Type> MethodThatShouldCallCustomMethodOnMocks()
    {
        var customInterfaceInstances = ObjectFactory.GetAllInstances<ICustomInterface>();

        foreach (var instance in customInterfaceInstances)
              instance.CustomMethod();


        return ...
    }
}

passes the test! The difference is that instead of iterating with SelectMany, I use foreach, but the test results are different (in the second case, CustomMethods are called in mocks).

Can someone explain this behavior?

+4
source share
1 answer

, . SelectMany . IEnumerable . ToList() SelectMany(), IEnumerable, SelectMany.

+7

All Articles