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 ?
exam
Moq does not support mocking delegates. But you can create some interface, with method, which matches your delegate signature:
public interface IBar
{
void M(int number);
}
Then create mock, which implements this interface, and use this mock object to create delegate:
Mock<IBar> bar = new Mock<IBar>();
Foo foo = new Foo(bar.Object.M);
A a = new A(foo);
bar.Verify(x => x.M(5));
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, without Foo
delegate instance creation. But anyway, mocking delegates requires interface creation.
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);
You can do something like that:
public interface IWithFOOMethod
{
void FooAlikeMethod(int number);
}
Mock<IWithFOOMethod> myMock = new Mock<IWithFOOMethod>();
A a = new A(myMock.Object.FooAlikeMethod);
myMock.Verify(call => call.Foo(It.IsAny<int>()), Times.Once())
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);