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));
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);
As of at least Moq 4.5.28, you can mock and verify the Func as you would expect to be able to. I couldn't tell when this feature was added (according to the original question at some point this did not work).
[Test] public void TestFoobar() { var funcMock = new Mock<Func<IFooBarProxy>>(); var fooBar = new FooBar(funcMock.Object); fooBar.Process(); funcMock.Verify(x => x(), Times.AtLeast(2)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With