简体   繁体   English

如何为存储库方法设置 MVC mock.Setup 和.Returns,它具有输出参数和返回类型

[英]How to setup MVC mock.Setup and.Returns for a repository method, which has on out parameter and a return type

I need to mock a method in a repository, but the method has an out parameter and a return type (of type class ExBool, which sets statuses and error messages).我需要在存储库中模拟一个方法,但该方法有一个输出参数和一个返回类型(类型为 class ExBool,它设置状态和错误消息)。 It needs to return a list of account setups.它需要返回一个帐户设置列表。 These setups are applied to the data posted back from the view.这些设置应用于从视图发回的数据。 I would have preferred getting the real values (accountSetups) ex the Dbase, but seems I will need to create dummy values in the mock of that repository.我更愿意从 Dbase 中获取真实值 (accountSetups),但似乎我需要在该存储库的模拟中创建虚拟值。 So, the question is how do I set dummy values into the retrieved 'accountSetups'?所以,问题是如何将虚拟值设置到检索到的“accountSetups”中?

the test method will test whether the incoming concatenated string is in the format as specified by the accountsetups.测试方法将测试传入的连接字符串是否采用帐户设置指定的格式。

The repository (which is injected into a controller (with Ninject)):存储库(注入 controller(使用 Ninject)):

public interface IAccountSetupBo
{
    ExBool List(out List<AccountSetup> accountSetups);
}

My Test:我的测试:

ExBool result = new ExBool();  // this is the method's return type
private List<AccountSetup> accountSetups;  //This is the list of setups reurned by the 'out' parameter, in the List method.

[TestInitialize]
    public void SetUp()
    {
        // Inject with Mock, which creates a proxy..not a concrete instance
        mockedAccountSetupBo = new Mock<IAccountSetupBo>();
        mockedAccountSetupBo
            .Setup(x => x.List(out accountSetups))
            .Returns(result);
    }

Thanks谢谢

populate the collection prior to the setup在设置之前填充集合

ExBool result = new ExBool();  // this is the method's return type

[TestInitialize]
public void SetUp() {

    List<AccountSetup> accountSetups = new List<AccountSetup>() {
        //...populate with desired objects
    }

    // Inject with Mock, which creates a proxy..not a concrete instance
    mockedAccountSetupBo = new Mock<IAccountSetupBo>();
    mockedAccountSetupBo
        .Setup(x => x.List(out accountSetups))
        .Returns(result);
}

and it will lazy evaluated when the model is invoked.当 model 被调用时,它会延迟计算。

Another way could be to use delegate in the Callback hook provided by moq .另一种方法是在moq提供的Callback挂钩中使用delegate Something like this:是这样的:

public delegate void SetupOutList(out List<AccountSetup> a);

mockedAccountSetupBo
        .Setup(x => x.List(out It.Ref<List<AccountSetup>>.IsAny))
        .Callback(new SetupOutList((out List<AccountSetup> a) => 
        {
            a = new List<AccountSetup>{...}; // initialize your list
        })
        .Returns(result);

Take a look at the official documentation about the callbacks .查看有关回调的官方文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM