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.
Moq does not support mocking delegates. But you can create some interface, with method, which matches your delegate signature:
Then create mock, which implements this interface, and use this mock object to create delegate:
After exercising your sut, you will be able to verify expectations on your mocked object.
UPDATE: Actually you can simply pass
bar.Object.M
to your sut, withoutFoo
delegate instance creation. But anyway, mocking delegates requires interface creation.What about using an anonymous function? It can act like an inline mock here, you don't need a mocking framework.
You can do something like that:
As of this commit Moq now supports the mocking of delegates, for your situation you would do it like so:
Then you can verify the delegate was invoked:
Or:
Since Moq doesn't support mocking delegates, I'll usually handle this with something like:
where the delegate provided performs some simple, verifiable action.