Invoking Actions from Moq

北城余情 提交于 2020-01-01 06:43:13

问题


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


来源:https://stackoverflow.com/questions/17167081/invoking-actions-from-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!