簡體   English   中英

如何模擬命令服務以調用其調用的私有方法?

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

我有一個帶責任的CommandController類,向CommandService提供模塊命令。 為了隱藏實現,該類注冊命令並在實現中包含私有方法,如下所示:

internal class CommandController
{
    private ICommandService commandService;

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

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

我該如何在模擬ICommandService的單元測試中測試ExecuteExampleCommand,以便一次不測試多個類(無論如何我都不會在UT環境中注冊該服務)?

我希望這個問題足夠清楚。

我可能是錯的,但我認為應將方法“ ExecuteExampleCommand”提取到一個類,例如“ ExampleCommandHandler ”。 然后,在Register命令中,您將傳遞命令和ExampleCommandHandler ,后者可以被模擬

internal class CommandController
{
    private ICommandService commandService;

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

    private ExampleCommandHandler exampleCommandHandler;
}

internal class ExampleCommandHandler : ICommandHandler
{
    void Execute()
    {
    }
}

要不就

this.commandService.Register("ExampleCommand", new ExampleCommandHandler())

您可以使用WhenCalled輕松訪問模擬的方法調用參數。 例如,如果您要執行傳遞給Register操作,則可以執行以下操作:

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

調用RegisterCommands ,mock將執行您的私有方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM