Aakash Singh
Aakash Singh

Reputation: 57

Hooks not running in Cucumber 4

@Before and @After methods of hooks are not running while running the Runner class.

I am using the dependencies: cucumber-java 4.3.0 cucumber-jvm 4.3.0

All steps in stepdef file are running fine except hooks. Is it some issue with latest cucumber version?

public class Hooks {
@Before
public void beforeHooks() {
    System.out.println("Run Before Scenario");
}

@After
public void afterHooks() {
    System.out.println("Run After Scenario");
}

Upvotes: 1

Views: 9282

Answers (1)

First Make sure you are using cucumber.api.java.Before (interface) rather than org.junit.Before as Cucumber will not process JUnit annotations.

  • @Before - import cucumber.api.java.Before;
  • @After - import cucumber.api.java.After;

Hope we are on the same page here and let's move further without making any delay.

Second lets understand in case your STEPS IMPLEMENTATION METHODS and HOOK CLASS is in the same package then we do not need to specify path of Hooks class additionally in the glue option of runner. In my case, i do have both in same package so we need to set only one package.

But if they are in the different packages then please include the package of the Hooks class in the glue option of the runner file.

Cucumber Runner :

package com.jacksparrow.automation.suite.runner;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/functional/",
                     glue = {"com.jacksparrow.automation.steps_definitions.functional" },
                   plugin = { "pretty","json:target/cucumber-json/cucumber.json",
                            "junit:target/cucumber-reports/Cucumber.xml", "html:target/cucumber-reports"},
                   tags = { "@BAMS_Submitted_State_Guest_User" },
                   strict = false,
                   dryRun = false,
               monochrome = true)

public class RunCukeTest {
}

Key Point: We shall not mix direct & transitive dependencies specially their versions! Doing so can cause unpredictable outcome. You can add below set of cucumber minimal dependencies.

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>4.3.0</version>
    <scope>test</scope>
</dependency>

Upvotes: 10

Related Questions