Moq& C#:回调无效。使用参数设置方法不能使用参数调用回调

时间:2017-05-16 11:48:15

标签: c# unit-testing moq

实际的界面签名就像这样

Task<GeneralResponseType> UpdateAsync(ICustomerRequest<IEnumerable<CustomerPreference>> request, CancellationToken cancellationToken, ILoggingContext loggingContext = null);

测试用例:

ICustomerRequest<IEnumerable<CustomerPreference>> t = null;
CancellationToken t1 = new CancellationToken();
LoggingContext t2 = null;
this.customerPreferenceRepositoryMock.Setup(x => x.UpdateAsync(
        It.IsAny<ICustomerRequest<IEnumerable<CustomerPreference>>>(),
        It.IsAny<CancellationToken>(),
        It.IsAny<LoggingContext>()))
    .Callback<ICustomerRequest<IEnumerable<CustomerPreference>>,CancellationToken, LoggingContext>((a, b, c) => { t = a ; t1 =b;t2= c; });

设置在测试用例中抛出异常,如下所示

  

无效的回调。使用参数设置方法   (ICustomerRequest 1,CancellationToken,ILoggingContext) cannot invoke callback with parameters (ICustomerRequest 1,的CancellationToken,LoggingContext)。

我在做什么错?

我已核实Moq: Invalid callback. Setup on method with parameters cannot invoke callback with parameters

但我没有看到任何帮助。

1 个答案:

答案 0 :(得分:2)

如评论中所述,使用的Callback参数与方法定义不匹配。即使Setup使用It.IsAny<LoggingContext>,方法定义也会使用ILoggingContext参数

t2更改为

ILoggingContext t2 = null;

并将Callback更新为

.Callback<ICustomerRequest<IEnumerable<CustomerPreference>>,CancellationToken, ILoggingContext>((a, b, c) => { 
    t = a; 
    t1 = b;
    t2 = c; 
});

.Callback((ICustomerRequest<IEnumerable<CustomerPreference>> a, 
           CancellationToken b, 
           ILoggingContext c) => { 
        t = a; 
        t1 = b;
        t2 = c; 
    });

无论哪种方式都可行。

我还建议Setup返回一个已完成的Task,以便允许测试按预期异步流动。

this.customerPreferenceRepositoryMock
    .Setup(x => x.UpdateAsync(
        It.IsAny<ICustomerRequest<IEnumerable<CustomerPreference>>>(),
        It.IsAny<CancellationToken>(),
        It.IsAny<LoggingContext>()))
    .Callback((ICustomerRequest<IEnumerable<CustomerPreference>> a, 
               CancellationToken b, 
               ILoggingContext c) => { 
                    t = a; 
                    t1 = b;
                    t2 = c; 
                    //Use the input to create a response
                    //and pass it to the `ReturnsAsync` method
             })
    .ReturnsAsync(new GeneralResponseType()); //Or some pre initialized derivative.

回顾Moq的QuickStart,以便更好地了解如何使用该框架。