How to write a code that will execute after each step is executed

cucumber before all features
cucumber before scenario
cucumber hooks order
testng annotations
cucumber close browser after each scenario
difference between hooks and background in cucumber
cucumber background
before suite in cucumber java

The application i am working throws a lot of unexpected alerts . I wanted to implement a way that catch all these through a common method isAlert present .

But how to call isAlertpresnt for each step in webdrriver , can anyone help me here ?

Typically my method would be like this :-

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        Alert alert = driver.switchTo().alert();
    } catch (Exception e) {
        //exception handling

The issue is how to call it before every step ? I know this will make my code slow but badly want this to be implemented .

I am looking for something which executes after each command\step in my test .Is this possible ?

Currently i am calling this method in all expected scenarios with a try catch.

WebDriver has WebDriverEventListener listener for what you are trying to do exactly. By implementing this listener and registering the driver - you can get this checkAlert method called behind the scenes before/after every action you will perform using webdriver.

Take a look at this example.

Cucumber Hooks, We'll look at an example where we use hooks to take screenshots during test execution. It's not necessary to define the same hooks in every glue code class. Methods annotated with @AfterStep execute after every step: Let's now look at what happens when we run a Cucumber scenario with all four� That is, begin executes once, and then it iterates: after each condition test, body and step are executed. If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.

Already one good answer is provided as by using event-listener.

Another simple way to handle, if your are using keywords/methods for all selenium actions. What i meant to say is, if you are using like click("locator") method to perform click in your test cases instead of writing driver command again and again, then you can insert that alert cross checking command after click in that click method.

 public void myClick(String myxpath){

    //calling checkAlert method to cross check

so if you are using methods like click, input etc for selenium actions, then you can try like above.

Thank You, Murali

What are Cucumber Hooks And How to Use Cucumber Hooks in Java, hooks, which are blocks of code that run before or after each scenario. You can define them anywhere in your project or step definition layers,� To indicate the results of its execution, a program can issue a return code. Using a COND parameter, you cantest the return code and, based on the test, either bypass or executea step. The COND parameter can be specified on either a JOB or EXEC statementby coding: //jobname JOB acct,progname,COND=(code,operator)//jobname JOB acct,progname,COND=((code,operator),(code,operator))//stepname EXEC PGM=x,COND=(code,operator)//stepname EXEC PGM=x,COND=(code,operator,stepname)//stepname EXEC

I could think of a solution using a Thread, which always monitors if there is any alert present, if yes then accept else don't do any thing. Considering you are using a testNG or Junit framework, here is the sample:

package poc.grid;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class Test {

    static WebDriver driver;

//This method returns a Thread, which monitors any alert and accept whenever finds it. And this return a Thread object.
public static Thread handleAlert(final WebDriver driver)
        Thread thread = new Thread(new Runnable() {
            public void run() {
                        System.out.println("Checking alert .... ");
                        System.out.println("Alert Accepted. ");
                    }catch(NoAlertPresentException n){
                        System.out.println("No Alert Present.  ");
                    }catch (Exception e) {
                        System.out.println("Exception: "+e.getMessage());

        return thread;

    public void beforeTest()
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        //In before Test, just call Thread and start it.

    //This is your normal Test
    public static void test() 

            int i=0;

        }catch(Exception e)
            System.out.println("Exception: "+e.getMessage());

    //At the end of test, you can stop the Thread.
    public void afterTest()


TestNG before and after annotations, The annotated method will be run after each test method. Let's try out an example containing all the preceding annotated methods and learn about when they are� After each increment, the value of num will increase by 1, and it will be printed on the screen. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on until the value of num becomes 10.

Cucumber - Hooks, Cucumber - Hooks - Cucumber hook allows us to better manage the code this notion better, let's take an example of a feature file and a step definition file. for this feature, this webdriver setup and cleanup will run with each given statement. test scenarios, and after hook gets executed after executing all the scenarios. the execution of the DATA step, but they are not executed until after the DATA step completes. in pre-macro times one used PUT statements to write SAS code to a file and then used ‘%oINCLUDE to execute it. We achieved essentially the same result by using the input stack instead of a new file. The main advantage is

Learn How to Use TestNG Annotations in Selenium (with Examples), To put it simply, TestNG annotations are lines of code that are inserted in the program/ For example, compile and run the below script and notice the execution order. It will System.out.println( "After Method will execute after every test method " ); We can break the test script process in to below steps:. When the CreateRegistryKey.ps1 script is run and there is no registry key present, the first debug line in the command displays the path to the script that is being executed. Because Windows PowerShell parses from the top down, the next line that is executed is the line that creates the Add-RegistryValue function.

Hooking into the Test Process, You've learned how to write step definitions and that with Gherkin you can What if you want to execute some code before the whole test suite or after a specific scenario? The AfterSuite event happens after all features in the suite have run. Java program execution follows 5 majors steps: Edit Compile Load Verify and Execute 1. Edit - Here the programmer uses a simple editor or a notepad application to write the java program and in the end give it a .java extension 2.

  • Are you using any test framework such as junit or testng to run the tests? You may look at available annotations.
  • I am using TestNG framework . But i Could not see any matching annotations which execute after each command
  • Thanks Murali , I would try this in my next framework .I think we have spoken before on selenium training :)
  • hoo..sorry, i am not remember previous discussion if happens, any how stack is very good platform to get helps and also i will try best..