开发者

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 = MockRep开发者_如何学JAVAository.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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜