Configuring Scenarios

JBehave 2 supports an out-of-the-box default configuration to enable you to get up and running quickly – as explained in the Two-minute tutorial.
it also is very configurable and customizable to support more advanced requirements.

We have learned from the tutorial that the central class for running scenarios in JBehave 2 is the
Scenario class, which we extend providing our own Steps. Scenario also allows the injection of a Configuration, which defaults to MostUsefulConfiguration, which can be customized to suit different user requirements.

For example, if we wanted to write scenarios using a different scenario name-to-class mapping we’d need to configure a bespoke ScenarioDefiner. E.g. to use extension ”.scenario” on the text files, we’d use

public class TraderSellsAllStocks extends Scenario {
 
    public TraderSellsAllStocks() {
        this(Thread.currentThread().getContextClassLoader());
    }
 
    public TraderSellsAllStocks(final ClassLoader classLoader) {
        super(new PropertyBasedConfiguration() {
            public ScenarioDefiner forDefiningScenarios() {
                return new ClasspathScenarioDefiner(
                    new UnderscoredCamelCaseResolver(".scenario"), 
                    new PatternScenarioParser(this), classLoader);
            }
        }, new StockSteps());
    }
}

And if we wanted to associate scenario TraderSellsAllStocks.class with TraderSellsAllStocks.scenario, we’d replace
UnderscoredCamelCaseResolver with CasePreservingResolver.

Note: The Scenario implementation explicitly declares a dependency on the ClassLoader, and provides a default value (the current thread context ClassLoader). This is important because it allows it to play well when running in systems that are more picky about classloading (e.g. Maven). It also honours the dependency injection paradigm of not putting dependency logic in the implementation.

Similarly, we can provide bespoke implementations for each element of the Configuration:

public interface Configuration {
    ScenarioDefiner forDefiningScenarios();
    ScenarioReporter forReportingScenarios();
    PendingErrorStrategy forPendingSteps();
    StepCreator forCreatingSteps();
    ErrorStrategy forHandlingErrors();
    KeyWords keywords();
}