Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying a delegate was called with Moq

i got a class that gets by argument a delegate. This class invokes that delegate, and i want to unit test it with Moq. how do i verify that this method was called ?

example class :

public delegate void Foo(int number);  public class A {    int a = 5;     public A(Foo myFoo)    {       myFoo(a);    } } 

and I want to check that Foo was called. Thank you.

like image 219
Lironess Avatar asked Jun 12 '12 14:06

Lironess


2 Answers

As of this commit Moq now supports the mocking of delegates, for your situation you would do it like so:

var fooMock = new Mock<Foo>(); var a = new A(fooMock.Object); 

Then you can verify the delegate was invoked:

fooMock.Verify(f => f(5), Times.Once); 

Or:

fooMock.Verify(f => f(It.IsAny<int>()), Times.Once); 
like image 86
Lukazoid Avatar answered Sep 28 '22 04:09

Lukazoid


What about using an anonymous function? It can act like an inline mock here, you don't need a mocking framework.

bool isDelegateCalled = false; var a = new A(a => { isDelegateCalled = true});  //do something Assert.True(isDelegateCalled); 
like image 20
Ufuk Hacıoğulları Avatar answered Sep 28 '22 03:09

Ufuk Hacıoğulları