JGiven
JGiven copied to clipboard
Singleton Stages
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;
}
+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.