Invoking Actions from Moq

2019-04-01 03:44发布

问题:

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?

回答1:

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
        });