gpt4 book ai didi

c# - 使用最小起订量模拟代表 "Wrapper"

转载 作者:太空宇宙 更新时间:2023-11-03 22:15:03 25 4
gpt4 key购买 nike

本质上,我有一个用于“安全”调用委托(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"));

关于c# - 使用最小起订量模拟代表 "Wrapper",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393829/

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