简体   繁体   中英

Avoid switch statement in Jbehave steps

I'm working on jbehave scenario. My step uses switch statement. There could be plenty of such tabs. It means everytime I have to add another case statement.

How can I replace the switch statements with OOP?

Now I distinguish the tab by enum, as only string can be received from jbehave.

But I believe there is more elegant way.

When I open publication in Editor and go to Audience tab

@When("I open publication in Editor and go to $tab tab")
public void openEditorAndGoToTab(String tab){

    TaggingUiTabs enumTab = EnumTextMatcher.matchEnum(tab, 
    TaggingUiTabs.getAllTabs());

    editorWindow.goToTaggingUi();
    switch (enumTab){
        case AUDIENCE:
            taggingUi.goToAudienceTab();
            break;
    }
}

I have sometimes used a Map to avoid very long switches, eg like this:

private final Map<TaggingUiTabs, Runnable> actionMap;

public MyStepsClass() {
   actionMap.put(TaggingUiTabs.AUDIENCE, () -> taggingUi.goToAudienceTab());
   actionMap.put(TaggingUiTabs.OTHER_TAB, () -> taggingUi.goToOtherTab());
}

@When("I open publication in Editor and go to $tab tab")
public void openEditorAndGoToTab(String tab){

    TaggingUiTabs enumTab = EnumTextMatcher.matchEnum(tab, 
    TaggingUiTabs.getAllTabs());

    editorWindow.goToTaggingUi();
    actionMap.get(enumTab).run();
}

This way I can easily add more actions. I find it very useful whenever I cannot redesign the rest of the code to be more object-oriented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM