gpt4 book ai didi

c# - Moq & C# : Invalid callback. 带参数的方法设置无法调用带参数的回调

转载 作者:行者123 更新时间:2023-12-02 01:16:11 24 4
gpt4 key购买 nike

实际的接口(interface)签名是这样的

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

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

Invalid callback. Setup on method with parameters (ICustomerRequest1,CancellationToken,ILoggingContext) cannot invoke
callback with parameters
(ICustomerRequest
1,CancellationToken,LoggingContext).

我做错了什么?

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

但我没有看到任何帮助。

最佳答案

正如评论中提到的 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.

查看最小起订量 QuickStart更好地了解如何使用该框架。

关于c# - Moq & C# : Invalid callback. 带参数的方法设置无法调用带参数的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com