本质上,我有一个用于“安全”调用委托(delegate)的类。 “安全”本质上意味着如果某个成员已经被处置,则调用将被跳过。此类的代码:
public class SafeOperationInvoker<TResponse> : IOperationInvoker<TResponse>
where TResponse : class
{
private readonly IDisposableResource _callbackOwner;
private readonly IOperationInvoker<TResponse> _next;
public SafeOperationInvoker(IDisposableResource callbackOwner, IOperationInvoker<TResponse> next)
{
_callbackOwner = callbackOwner;
_next = next;
}
public void Invoke(Action<TResponse> completedCallback)
{
//wrap the callback
_next.Invoke(response => SafeOperationCompleted(response, completedCallback));
}
private void SafeOperationCompleted(TResponse response, Action<TResponse> completedCallback)
{
//only invoke the callback if not disposed
if (_callbackOwner != null && _callbackOwner.IsDisposed)
{
return;
}
completedCallback(response);
}
}
我想要测试 SafeOperationCompleted 方法——如果 callbackOwner 被释放,completedCallback 不会触发(反之亦然)。
我手工创建了一个假的,使我的测试正常运行:
private class FakeOperationInvoker : IOperationInvoker<string>
{
public void Invoke(Action<string> completedCallback)
{
completedCallback("hi");
}
}
测试:
[TestMethod]
public void SafeOperationCompleted_OriginalCallback_Invoked()
{
int called = 0;
var mockOwner = new Mock<IDisposableResource>();
mockOwner.Setup(m => m.IsDisposed).Returns(false);
var invoker = new SafeOperationInvoker<string>(mockOwner.Object, new FakeOperationInvoker());
invoker.Invoke((o) => { called++;});
Assert.AreEqual(1, called, "Original callback should have been called");
}
我想做的是使用 moq 创建一个模拟,其行为方式与 FakeOperationInvoker 的行为方式相同。我怎样才能做到这一点?
难道你不能这样做吗:
var operationInvoker = new Mock<IOperationInvoker<string>>();
operationInvoker.Setup(oi => oi.Invoke(It.IsAny<Action<string>>())
.Callback((Action<string>> callback) => callback("hi"));
我是一名优秀的程序员,十分优秀!