Search code examples
javabddjbehave

Best way to setup fixture data for JBehave tests


Let's say we have multiple test like this:

Scenario:  trader is not alerted below threshold

Given a stock of symbol STK1 and a threshold of 10.0
When the stock is traded at 5.0
Then the alert status should be OFF

but the twist is that all the "Given" setup has to be done before any testes are ran. What would be the best way to do this?


Solution

  • Check http://jbehave.org/reference/stable/story-syntax.html for Lifecycle: steps in story files. But watch out, those are executed before/after EACH scenario.

    There are @BeforeStory and @AfterStory annotations as well, they are quite obvious to use, but you may want to check the documentation: http://jbehave.org/reference/stable/annotations.html.

    However, you may feel that it would be better to have everything in your story file... As much as I know, you cannot define a step in the story file, that runs before executing the story.

    I also ran into the 'lack' of this feature before, but i think the reason why it was not implemented is that it would not fit the BDD approach, that scenarios should be independently executable and understandable. These steps are often related to some kind of environment preparation (globally for all the scenarios), which are not important for human readers(stakeholders) and thus should not be the part of the 'User story description' which the .story file is supposed to be.

    If there is no major performance issue, I found that - from readability point of view - it is better to run these setup/teardown stuff before each and every scenario. If you use the Lifecycle: steps, you won't end up in duplications, and it will be clear for any human reader what steps should be done to execute the test just by reading the story file. But that's just my opinion.

    So I think you have these options:

    1. run your steps before/after each scenario by using LifeCycle: steps
    2. use @BeforeStory and @AfterStory annotations
    3. define a dummy scenario with your setup/teardown steps as the first/last scenario of your story file and name it so that it is clear for everybody that it is just a 'technical' scenario. By default the order of the scenarios are fixed, so this might do the trick. (hackish...)
    4. write steps in the Lifecycle: part, and hack the implementation of these steps so that they are executed once in a story (even more hackish)