基本上我有一个用于“安全”调用委托的类。 “安全”实质上意味着如果某个成员已被处置,则将跳过调用。这个类的代码:
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行为相同的模拟方法。我怎样才能做到这一点?
答案 0 :(得分:4)
你不能这样做:
var operationInvoker = new Mock<IOperationInvoker<string>>();
operationInvoker.Setup(oi => oi.Invoke(It.IsAny<Action<string>>())
.Callback((Action<string>> callback) => callback("hi"));