Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Actions from Moq

I've got a service with a method that takes two Actions, one for success and one for failure. Each Action takes a Result parameter that contains additional information...

void AuthoriseUser(AuthDetails loginDetails, 
  Action<AuthResult> onSuccess, 
  Action<AuthResult> onFailure);

I'm writing a unit test for a class that is dependant on that service, and I want to test that this class does the correct things in the onSuccess(...) and onFailure(...) callbacks. These are either private or anonymous methods, so how do I setup the mocked service to call either Action?

like image 741
GoatInTheMachine Avatar asked Jun 18 '13 10:06

GoatInTheMachine


1 Answers

You can use the Callback method (see also in the Moq quickstart Callbacks section) to configure a callback which gets called with the original arguments of the mocked method call (AuthoriseUser) so you can call your onSuccess and onFailure callbacks there:

var moq = new Mock<IMyService>();
moq.Setup(m => m.AuthoriseUser(It.IsAny<AuthDetails>(),
                                It.IsAny<Action<AuthResult>>(),
                                It.IsAny<Action<AuthResult>>()))
    .Callback<AuthDetails, Action<AuthResult>, Action<AuthResult>>(
    (loginDetails, onSuccess, onFailure) =>
        {
            onSuccess(new AuthResult()); // fire onSuccess
            onFailure(new AuthResult()); // fire onFailure
        });
like image 130
nemesv Avatar answered Jan 03 '23 21:01

nemesv