mock

Mock and callback a generic method with unavailable type using Moq

This is as much a note to self as a blog post. I needed to test a method that was dependent on a API with a callback action where T was scoped internal in the library that I was testing. Rather than making the type public I went ahead and tried to mock it anyway 😀

The code that we want to test is called from third party API like

await hubProxyFactory
            .Create(hubUrl, configureConnection, async p =>
                {
                    proxy = p;
                    await SendQueuedSubscriptions();
                    p.On<Message>("onEvent", OnEvent);
                },
                Reconnected, FaultedConnection, ConnectionComplete);

Message is a private type and OnEvent is of type Action<Message>. Its the OnEvent method we want to test. So we need to mock On<T> without knowing T and we need to save a reference to the OnEvent even though T is unknown. It looks like this

                    mock.Setup(x => x.On("onEvent", It.IsAny<Action<It.IsAnyType>>())).Callback(
                        (string e, MulticastDelegate callback) =>
                        {
                            onEvent = callback;
                        });
(more…)