Search code examples
c#unit-testingrhino-mocks

How to mock a command service to call private methods called by it?


I have a CommandController class with one responsibilty, provide to the CommandService the Module commands. To hide the implementation the class registers the commands and contain private methods with the implementation, something like this:

internal class CommandController
{
    private ICommandService commandService;

    public void RegisterCommands()
    {
        this.commandService.Register("ExampleCommand", this.ExecuteExampleCommand);
    }

    private void ExecuteExampleCommand()
    {
        ... implementation here ...
    }
}

How can I test the ExecuteExampleCommand in a unit test mocking the ICommandService so I don't test more than one class at a time (anyway it's likely that I won't have the service registered in a UT environment)?

I hope the question is clear enought.


Solution

  • You can easily access mock's method invocation arguments using WhenCalled. For example, if you want to execute action passed to Register you can do this:

    registry.Stub(r => r.Register(
            Arg<String>.Is.Equal("ExampleCommand"),
            Arg<Action>.Is.Anything))
        .WhenCalled(invocation => ((Action) invocation.Arguments[1])());
    

    When RegisterCommands is called, mock will execute your private method.