简体   繁体   中英

Mocking a Delegate “Wrapper” Using Moq

Essentially I have a class that is used for "safe" invocation of delegates. "Safe" essentially means that if a certain member is already disposed, the invocation will be skipped. The code for this class:

    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);
    }
}

What I want is to test the SafeOperationCompleted method--if the callbackOwner is disposed, the completedCallback does not fire (and vice versa).

I have created a fake by hand that makes my test function correctly:

private class FakeOperationInvoker : IOperationInvoker<string>
{
    public void Invoke(Action<string> completedCallback)
    {
        completedCallback("hi");
    }
}

The test:

[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");
}

What I would like to do is use moq to create a mock that behaves the same way that FakeOperationInvoker behaves. How can I achieve this?

Can't you just do:

var operationInvoker = new Mock<IOperationInvoker<string>>();
operationInvoker.Setup(oi => oi.Invoke(It.IsAny<Action<string>>())
                .Callback((Action<string>> callback) => callback("hi"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM