从Moq调用操作 [英] Invoking Actions from Moq

查看:247
本文介绍了从Moq调用操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,有一个方法,需要两个行动,一个是成功,一个失败。每个 Action 采用包含其他信息的Result参数...

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

我正在为依赖于该服务的类编写单元测试,测试这个类在 onSuccess(...) onFailure(...)回调。这些是私人或匿名方法,所以如何设置模拟服务来调用Action?

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?

推荐答案

回调方法(请参阅 Moq快速入门回调部分)配置一个回调,该回调用mocked方法调用( AuthoriseUser )的原始参数调用,因此您可以调用 onSuccess onFailure 回调有:

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

这篇关于从Moq调用操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆