Tip: Mocking callbacks using RhinoMocks when lambdas are involved

There is several cool language features available in C# 3.0, one of them is lambdas. It’s a handy tool when you want to execute a few lines of code where a delegate is expected. Fredrik Normén and I chatted about one of those places today, callbacks in async scenarios.

Given this callback:

public string ResultOfServiceCall { get; private set; }
public ContextThatDoesStuff(IServiceWithCallback service)
            () => ResultOfServiceCall = service.End()

How would you set up a mock to handle that? Somehow you need to intercept that lambda and execute it. One way, there might be others, to solve this with RhinoMocks is to use the WhenCalling feature. A simple test to demonstrate:


public void TheTest()
    var mock = MockRepository.GenerateMock<IServiceWithCallback>();

    mock.Expect(service => service.Begin(null))
        .WhenCalled(invocation => ((Action)invocation.Arguments[0]).Invoke());

    mock.Expect(service => service.End())
        .Return("The String");

    var context = new ContextThatDoesStuff(mock);

    Assert.AreEqual(context.ResultOfServiceCall, "The String");

In the above example we capture the in parameter, here it’s a lambda, casting it to an Action delegate and invoke it.

I just love the flexibility in RhinoMocks, don’t you?

Leave a Reply

Your email address will not be published. Required fields are marked *