【问题标题】:Moq & C#: Invalid callback. Setup on method with parameters cannot invoke callback with parametersMoq & C#:无效的回调。设置带参数的方法不能调用带参数的回调
【发布时间】:2017-06-29 21:34:21
【问题描述】:

实际的接口签名是这样的

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

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

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

我做错了什么?

我已验证Moq: Invalid callback. Setup on method with parameters cannot invoke callback with parameters

但我没有看到任何帮助。

【问题讨论】:

  • 应该是ILoggingContext 而不是LoggingContext

标签: c# unit-testing moq


【解决方案1】:

如 cmets 中所述,使用的 Callback 参数与方法定义不匹配。即使Setup 使用It.IsAny&lt;LoggingContext&gt; 方法定义使用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 以更好地了解如何使用该框架。

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多