Search code examples
c#rhino-mocks

How do I stub a Func<T,TResult> in Rhino Mocks?


I have a class with a dependency:

private readonly IWcfClient<ITestConnectionService> _connectionClient;

and I want to stub out this call:

_connectionClient.RemoteCall(client => client.Execute("test"));

This currently isn't working:

_connectionService
    .Stub(c => c.RemoteCall(rc => rc.Execute("test")))
    .Return(true);

Is this possible in Rhino?


Solution

  • Use a custom Do delegate that takes in the func and test that. You can do it by converting it to an expression and parsing the expression tree, or just run the delegate with a mock input and test the results.

    The following will throw an error if the lambda inside RemoteCall() does not contain x=>x.Execute("test") - you can work off of the idea to get it to do exactly what you want.

    public interface IExecute {
      void Execute(string input)
    }
    _connectionService
        .Stub(c => c.RemoteCall(null)).IgnoreArguments()
        .Do(new Func<Action<IExecute>,bool>( func => {
           var stub = MockRepository.GenerateStub<IExecute>();
           func(stub);
           stub.AssertWasCalled(x => x.Execute("test"));
           return true;
         }));;