c# - 如何使用 moq 设置 Dispatcher InvokeAsync 方法
问题描述
我是单元测试的新手,并尝试通过编写包装器方法来模拟 Dispatcher,但我无法将该InvokeAsync
方法设置为回调。
IDispatcher:
public interface IDispatcher
{
// other implementations
DispatcherOperation InvokeAsync(Action action);
DispatcherOperation<TResult> InvokeAsync<TResult>(Func<TResult> callback);
}
DispatcherWrapper:
public class DispatcherWrapper : IDispatcher
{
// Other implementations
public DispatcherOperation InvokeAsync(Action action)
{
return this.UIDispatcher.InvokeAsync(action);
}
public DispatcherOperation<TResult> InvokeAsync<TResult>(Func<TResult> callback)
{
return this.UIDispatcher.InvokeAsync(callback);
}
}
我尝试设置它的方式:
// this works as expected
this.mockDispatcher.Setup(x => x.BeginInvoke(It.IsAny<Action>())).Callback((Action a) => a());
// get an exception : System.ArgumentException : Invalid callback. Setup on method with parameters (Func<Action>) cannot invoke callback with parameters (Action).
this.mockDispatcher.Setup(x => x.InvokeAsync(It.IsAny<Func<It.IsAnyType>>())).Callback((Action a) => a());
用法:
var res = await this.dispatcher.InvokeAsync(() =>
{
// returns a result by computing some logic
});
我只面临测试项目的问题。
解决方案
非泛型版本接受一个Action
参数:
mockDispatcher.Setup(x => x.InvokeAsync(It.IsAny<Action>())).Callback((Action a) => a());
通用版本接受Func<TResult>
:
mockDispatcher.Setup(x => x.InvokeAsync(It.IsAny<Func<It.IsAnyType>>())).Callback(() => /* ... */ });
如果要Func<TResult>
在回调中调用 ,则应指定类型参数或捕获Func<TResult>
:
Func<int> someFunc = () => 10;
mockDispatcher.Setup(x => x.InvokeAsync(It.IsAny<Func<It.IsAnyType>>())).Callback(() => someFunc());
推荐阅读
- curl - 如何正确安装 libcurl 以在 Visual Studio 2017 中使用?
- dart - 在 Flutter 中的屏幕之间传递数据
- sql - 如何在plsql中进行数据透视
- chapel - 如何打印出 Chapel 变量的完全限定类型?
- lightgbm - 如何使用 LightGBM 拟合函数曲线?
- sql-server - 创建一个触发器来记录和更新对表的更改
- javascript - 如何在 Angular 的延迟加载模块中保持表单状态?
- java - imageview翻译后计算新的点坐标
- google-maps - 我可以在使用 Device.OpenUri 到达目的地后导航回我的应用程序吗?
- r - 查找和估算单词(字符串)的质心