Search code examples
c#unit-testingrhino-mocks

Improving Mocking Delegates


I am using Rhino Mocks. I have a data repository, a small part of it is defined like this,

interface IDataRepository
{
    void GetCurrentUserId(Action<int?> callback);
}

This is on the client side of a silverlight RIA services application, thus why we have an Action callback. This will callback once the operation has been completed on the server, and there is a result.

To unit test something that calls that method I end up doing this,

private delegate void GetCurrentUserIdDelegate(Action<int?> callback);

private void GetCurrentUserId(Action<int?> callback)
{
    callback.Invoke(10);
}

[TestMethod]
public void TestBlah()
{
    var mockRepository = MockRepository.GenerateMock<IDataRepository>();

    mockRepository.Expect(r => r.GetCurrentUserId(null)).IgnoreArguments().Do(new GetCurrentUserIdDelegate(GetCurrentUserId));
}

It works fine, but it seems very verbose. Isn't there a more concise way of doing it?

I am going to have to define a delegate for each of the methods in the IDataRepository interface that have callbacks in them. To me this seems a bit messy, hard to maintain, etc.

Perhaps there is an inline way of doing it without needing to define the delegates?


Solution

  • The delegate you pass should just have the same signature as the mocked method, so in your case you can use Action<Action<int?>>:

    mockRepository
        .Expect(r => r.GetCurrentUserId(null))
        .IgnoreArguments()
        .Do(new Action<Action<int?>>(act => { act(10); }));