Using Moq to Mock a Func<> constructor parameter and Verify it was called twice

thehumansaredead picture thehumansaredead · Feb 6, 2013 · Viewed 18.9k times · Source

Taken the question from this article (How to moq a Func) and adapted it as the answer is not correct.

public class FooBar
{
    private Func<IFooBarProxy> __fooBarProxyFactory;

    public FooBar(Func<IFooBarProxy> fooBarProxyFactory)
    {
        _fooBarProxyFactory = fooBarProxyFactory;
    }

    public void Process() 
    {
        _fooBarProxyFactory();
        _fooBarProxyFactory();
    }
}

I have a need to mock a Func<> that is passed as a constructor parameter, the assert that the func was call twice.

When trying to mock the function var funcMock = new Mock<Func<IFooBarProxy>>(); Moq raises and exception as the Func type is not mockable.

The issue is that without mocking the func it is not possible to verify that the func was called (n) times. funcMock.Verify( (), Times.AtLeast(2));

Answer

Daniel Hilgarth picture Daniel Hilgarth · Feb 6, 2013

I don't think it is necessary to use a mock for the Func.

You can simply create an ordinary Func yourself that returns a mock of IFooBarProxy:

int numberOfCalls = 0;
Func<IFooBarProxy> func = () => { ++numberOfCalls;
                                  return new Mock<IFooBarProxy>(); };

var sut = new FooBar(func);

sut.Process();

Assert.Equal(2, numberOfCalls);