如何使用最小起订量设置 Dispatcher InvokeAsync 方法

How do I setup Dispatcher InvokeAsync Method using moq

我不熟悉单元测试并尝试通过编写包装器方法来模拟 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());