MOQ 'TestMethod(Action<int> callback)' and be able to 'call' callback

c#, moq, testing

Solution

try this:

myMock.Setup(m => m.TestMethod(It.IsAny<Action<int>>())).Callback<Action<int>>((action) => action(4));

although this seems a rather convoluted way to essentially test your callback method. Why not test it directly?

Problem

Oook, I'm wanting to mock a callback that I know my service will call. For example: ``` public interface ITestMe { void TestMethod(Action<int> callback); } ``` In the application, when calling 'TestMethod' I would pass the callback method to hit after it has run, which will do something based on the parameters. Typically, in this case it's used like this: ``` ... testMe.TestMethod( (ret) => { if(ret < 0) AddToErrorCollection(ret); else AddToSuccessCollection(ret); } ); ``` What I'd like to do in MOQ is call that anonymous method with a range of values i.e. something like: ``` myMock.Setup(m => m.TestMethod(It.IsAny<Action<int>>())).... //Call that action!!?? ``` Is there anyway to do that? Is this even the correct way to do it?

Original source