【问题标题】:Further customize Return value using MOQ使用 MOQ 进一步自定义返回值
【发布时间】:2016-05-25 17:28:40
【问题描述】:

我有以下单元测试。

[TestMethod]    
    public void IfTheSecondPaymentFailsThenTheFirstPaymentShouldBeVoided()
    {
        var iPaymentMock = new Mock<IPaymentMock>();
        var paymentSpecificationResponse = new PreregisteredAccountSpec();   
        iPaymentMock.Setup(
                counter => counter.ProcessPayment
                    (
                        It.IsAny<Context>(),
                        It.IsAny<PreregisteredAccountSpec>(),  
                        It.IsAny<Guid>())
                    ).
                 Returns((Context context, PaymentSpecification spec, Guid guid) =>
                {
                    return paymentSpecificationResponse;
                }
                );
    }

当 Distributions 数组为只读时,如何更改测试以将 paymentSpecificationResponse.Distributions[0].Transaction.GetVendorId() 返回为“1”。

【问题讨论】:

    标签: c# .net unit-testing moq


    【解决方案1】:

    如果我理解正确,您想根据传递给它的参数更改模拟返回值。您可以使用.Returns() 的重载并提供一个函数。

    .Returns((context, spec, guid) => { //Do something with the arguments passed to the mock })
    

    【讨论】:

    • 我想我的问题应该是:当我无法“设置” paymentSpecificationResponse.Distributions[0] 时,我应该如何更改 paymentSpecificationResponse? paymentSpecificationResponse 是第三方 dll 的一部分。
    • 我现在明白了。不幸的是,无法看到第三方类,很难给出明确的答案。有没有可以调用的SetVendorId() 函数?您可以将.Transaction 设置为模拟吗?
    • 事实上,他们有一个 AddDistribution 方法来添加一个分布。创建一个有效的分布并使用 AddDistribution 方法添加它对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多