Moq 和 C#:回调无效。带参数的方法设置无法调用带参数的回调

Mur*_*hna 4 c# unit-testing moq

实际的接口签名是这样的

Task<GeneralResponseType> UpdateAsync(ICustomerRequest<IEnumerable<CustomerPreference>> request, CancellationToken cancellationToken, ILoggingContext loggingContext = null);
Run Code Online (Sandbox Code Playgroud)

测试用例:

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; });
Run Code Online (Sandbox Code Playgroud)

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

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

我做错了什么?

我已验证起订量:回调无效。带参数的方法设置无法调用带参数的回调

但我没有看到任何帮助。

Nko*_*osi 5

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

改成t2

ILoggingContext t2 = null;
Run Code Online (Sandbox Code Playgroud)

并更新Callback

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

或者

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

无论哪种方式都会起作用。

我还建议返回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.
Run Code Online (Sandbox Code Playgroud)

查看 Moq 的快速入门以更好地了解如何使用该框架。