[CUCUMBER] @Before and @After running multiple times in multiple step definition files

1,163 views
Skip to first unread message

shivi malviya

unread,
Sep 20, 2013, 1:20:58 AM9/20/13
to cu...@googlegroups.com
Hi All,

I am facing issue while running my Cucumber tests in Java. I have created multiple step definition files for feature files and each step definition has @Before and @After defined for browser initialization.
So when I am running my test with command :
mvn test -Dcucumber.options="classpath:LanguageCookie.feature"

Then @Before and @After is running for all the step definition files, i.e. it is running multiple times though I want to execute it only once.

Please suggest what should I do to control this.

Thanks,
Shivi

Paolo Ambrosio

unread,
Sep 20, 2013, 2:34:46 AM9/20/13
to cu...@googlegroups.com
On Fri, Sep 20, 2013 at 6:20 AM, shivi malviya <malviy...@gmail.com> wrote:

> Hi All,
>
> I am facing issue while running my Cucumber tests in Java. I have created
> multiple step definition files for feature files and each step definition
> has @Before and @After defined for browser initialization.
> So when I am running my test with command :
> mvn test -Dcucumber.options="classpath:LanguageCookie.feature"
>
> Then @Before and @After is running for all the step definition files, i.e.
> it is running multiple times though I want to execute it only once.

Hi Shivi,

This is the intended behaviour of the @Before and @After hooks: they
are not related to each step definition. Every hook is run on each
scenario (unless it's filtered out by tags). Take a look at the
java-webbit-websockets-selenium example in cucumber-jvm sources to
find out how to deal with browser initialization.


Paolo

Dale Highfill

unread,
May 9, 2015, 9:50:36 AM5/9/15
to cu...@googlegroups.com
We have a similar issue where we've taking an approach of a Step Definition per feature file because we're using Cucumber to test web services and to keep the organization clean, this makes the most sense to our implementation.  With multiple Step Definitions though, using @Before or @After caused us some issues. After reading Paolo's suggestion, it appears the solution to this is dependency injection.  For our web services, we're setting in some credentials from configuration values on the @Before, but by using Spring's IoC we'll provide a public constructor that will accept the credential configuration and set it into the StepDefinition.

I don't believe then with multiple Step Definitions classes, running across our web services the @Before or @After can be used. 
Reply all
Reply to author
Forward
0 new messages