JGiven icon indicating copy to clipboard operation
JGiven copied to clipboard

Singleton Stages

Open janschaefer opened this issue 10 years ago • 1 comments

It would sometimes be useful to have stages that live longer than a single scenario. For example, to do expensive setups that can be reused between tests. In JUnit this is typically done by using @BeforeClass annotations. However, that requires to have static fields which has several drawbacks.

Idea: Introduce a new kind of stage, namely singleton stages. Singleton stages can live longer than a single scenario and are reused between scenarios. In contrast to normal stages, a singleton stage can only be injected, it cannot be a real scenario stage.

  • Singleton stages can provide values to other stages, but no values are injected back into a singleton stage
  • Singleton stages only support @BeforeStage, @AfterStage, and @ScenarioRule life-cycle anotations.

Example:

public class MySingletonStage {
    @ProvidedScenarioState
    protected ExpensiveRessource expensiveRessource;

    @BeforeStage
    protected void setupExpensiveRessource() {
         expensiveRessource = ... // create ressource
    }

    @AfterStage
    protected void shutdownExpensiveRessource() {
         expensiveRessource.shutdown();
    }
}

Usage in other stage:

public class MyNormalStage {
    @SingletonStage
    protected MySingletonStage mySingletonStage;

    @ExpecedScenarioState
    protected ExpensiveRessource expensiveRessource;


}

janschaefer avatar Dec 06 '14 09:12 janschaefer

+1 for this one. I'm currently writing functional tests that need an application started, and for every @Test of a SimpleScenarioTest the application is started whereas I only need to do it once.

c100k avatar Jan 08 '16 10:01 c100k