user7637341
user7637341

Reputation: 481

Run after all cucumber tests

Is there a way to run a method after all of the cucumber tests have been run?

The @After annotation would run after every individual test, right? I wan't something that would only run once, but at the very end.

Upvotes: 10

Views: 21942

Answers (4)

Joe Caruso
Joe Caruso

Reputation: 1374

With TestNG suite annotations would work as well.

@BeforeSuite
public static void setup() {
    System.out.println("Ran once the before all the tests");
}

@AfterSuite
public static void cleanup() {
    System.out.println("Ran once the after all the tests");
}

Upvotes: 3

Michał Krzywański
Michał Krzywański

Reputation: 16900

What you could do is to register event handler for TestRunFinished event. For that you can create a custom plugin which will register your hook for this event :

public class TestEventHandlerPlugin implements ConcurrentEventListener {

    @Override
    public void setEventPublisher(EventPublisher eventPublisher) {
        eventPublisher.registerHandlerFor(TestRunFinished.class, teardown);
    }

    private EventHandler<TestRunFinished> teardown = event -> {
        //run code after all tests
    };
}

and then you will have to register the plugin :

  • if you are running cucumber CLI you can use -p/--plugin option and pass fully qualified name of the java class : your.package.TestEventHandlerPlugin
  • for Junit runner :
@RunWith(Cucumber.class)
@CucumberOptions(plugin = "your.package.TestEventHandlerPlugin") //set features/glue as you need.
public class TestRunner {

}

Upvotes: 3

Sadegh Rahmani
Sadegh Rahmani

Reputation: 1

cucumber is a scenario base test, you should write your own scenario in .feature file step by step and these steps are executed respectively by their step definitions.

So if you want something to happen after all steps, you should write it in the last step and develop this step in its step definition.

Also, for what you want to execute before other steps you should consider a step before all the steps in the .feature file and develop it in its step definition.

Upvotes: -5

Morvader
Morvader

Reputation: 2313

You could use the standard JUnit annotations.

In your runner class write something similar to this:

@RunWith(Cucumber.class)
@Cucumber.Options(format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"})
public class RunCukesTest {

    @BeforeClass
    public static void setup() {
        System.out.println("Ran the before");
    }

    @AfterClass
    public static void teardown() {
        System.out.println("Ran the after");
    }
}

Upvotes: 11

Related Questions