Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));

like image 827
thehumansaredead Avatar asked Feb 06 '13 12:02

thehumansaredead


Video Answer


2 Answers

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); 
like image 133
Daniel Hilgarth Avatar answered Sep 22 '22 03:09

Daniel Hilgarth


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)); } 
like image 42
ktam33 Avatar answered Sep 23 '22 03:09

ktam33