Cucumber Selenium Tutorial: Cucumber Java Selenium WebDriver Integration

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated January 18, 2025

Cucumber Selenium WebDriver Java Integration with Example:

In the last tutorial, we discussed the Cucumber tool, its usage, and different features.

Moving ahead in our free Selenium online training series, we will discuss how to set up a cucumber project and will discuss the integration of Selenium WebDriver with Cucumber.

We will set up a Cucumber project with Maven. To set up Maven in your system, please refer to this tutorial on Maven from the same series. 

Selenium WebDriver Integration With Cucumber

Cucumber Java Selenium WebDriver Integration

Cucumber Project Setup

Step #1: Create a New Maven Project:
Right Click -> New -> Others -> Maven -> Maven Project -> Next

Step #2: Now the project will look like this:

Cucumber Selenium 1

Step #3: Add the below dependencies in pom.xml

<dependencies>
<dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>1.0.2</version>
      <scope>test</scope>
  </dependency>
<dependency>
     <groupId>info.cukes</groupId>
     <artifactId>cucumber-junit</artifactId>
     <version>1.0.2</version>
     <scope>test</scope>
</dependency>
<dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.10</version>
     <scope>test</scope>
</dependency>
</dependencies>

Step #4: Create a sample.feature file under src/test/resources.

@smokeTest
Feature: To test my cucumber test is running
I want to run a sample feature file.

Scenario: cucumber setup

Given the sample feature file is ready
When I run the feature file
Then the run should be successful

Step #5: Create a class under src/test/java which will implement all the steps.

public class stepDefinition {
       @Given("^sample feature file is ready$")
       public void givenStatment(){
              System.out.println("Given statement executed successfully");
       }
       @When("^I run the feature file$")
       public void whenStatement(){
              System.out.println("When statement execueted successfully");
       }
       @Then("^run should be successful$")
       public void thenStatment(){
              System.out.println("Then statement executed successfully");
       }
}

Step #6: Create a JUnit runner to run the test.

@RunWith(Cucumber.class)
@Cucumber.Options(format={"pretty","html:reports/test-report"},tags= "@smokeTest")
public class CucumberRunner {
}

Provide the path of the report as given here. The reports will be stored in ‘test-report’ folder under the project folder and the “pretty” format specifies the type of report.

Step #7: Junit Result and Test Report:

Below is the report of when the cucumber test is successful. The green bar in Junit describes the test is passed. Similarly, the red bar describes the test has failed.

Cucumber Selenium 2

If we want to use default reporting, then navigate the path mentioned in Junit Runner. Here, we have given the path as reports->test-reports->index.html.

Open this report in Internet Explorer or Firefox to verify the result. Below is a sample of the report:

Cucumber Selenium 3

Cucumber Selenium WebDriver Integration

The cucumber framework can test the web-based applications along with Selenium WebDriver. The test cases are written in simple feature files that are easily understood by managers, non-technical stakeholders, and business analysts.

And those feature file steps are implemented in the step definition file. If you are using Maven, then you have to add dependencies for Cucumber and WebDriver.

So here is the sample test case we have implemented using Cucumber and WebDriver. As given below, the scenario in the feature file is self-explanatory.

Feature: Login Feature File
@selenium
Scenario: Login scenario test for Gmail

Given navigate to the Gmail page
When the user logs in using the username as “userA” and password as “password”
Then home page should be displayed

WebDriver Implementation in Cucumber stepDefinitions:

public class stepDefinition {
WebDriver dr;
@Given("^navigate to gmail page$")
public void navigate(){
       dr=new FirefoxDriver();
       dr.get("http://www.gmail.com");         
       }
@When ("^user logged in using username as \"(.*)\" and password as \"(.*)\"$")
public void login(String username,String password){
       dr.findElement(By.xpath("//*[@id='Email']")).sendKeys(username);
       dr.findElement(By.xpath("//*[@id='Passwd']")).sendKeys(password);
       dr.findElement(By.xpath("//*[@id='signIn']")).click();
       dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
       }
@Then("^home page should be displayed$")
public void verifySuccessful(){
      String expectedText="Gmail";
      String actualText=         dr.findElement(By.xpath("//*[@id='gbq1']/div/a/span")).getText();
      Assert.assertTrue("Login not successful",expectedText.equals(actualText));
      }
}

In this test, we have used Firefox as the browser to test the Gmail login functionality.
The WebDriver object is a class variable and is used across the class.

The given statement initializes the browser and navigates to the page.
When the statement logs into the application using the username as “userA” and password as “password”. Both the values ‘username’ and ‘password’ are passed from the feature file and both values are to be used in the same order.
Then Statement only validates the conditions after logging into the application.

This is a sample test describing the usage of Cucumber and Selenium. You can create multilayer architecture depending on your project requirements.

Conclusion

In this Cucumber Selenium Java Integration Tutorial, we have covered most of the Cucumber concepts, including Cucumber features, its usage, and WebDriver.

This reduces the complexity of code written to design the traditional frameworks like Keyword Driven and Hybrid Framework. Cucumber is used in most of the projects where people follow the agile methodology as Behavior Driven Development is an Agile Software practice.

Next Tutorial #32: We have now completed all technical tutorials from this Selenium training series. Next, we will post about a few important general topics like ‘effort estimation for Selenium projects’ and ‘Selenium interview questions with answers’.

Please post your queries regarding the Cucumber Selenium Tutorial.

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • Selenium on Chrome

    In-Depth Tutorial On ChromeDriver for Running Selenium Webdriver Tests on Chrome Browser: Handling browser alerts while automating through Selenium will be discussed in this article. Moreover, we will elaborate on the set up of the Selenium script for the Google Chrome browser along with appropriate examples and pseudo-codes. Upon going…

  • Introduction To Selenium WebDriver

    Introduction to Selenium WebDriver: Earlier in this series, we published tutorials that focused more on Selenium IDE and its various aspects. We introduced the tool and discussed its features. We also constructed a few scripts using Selenium IDE and Firebug. From there, we moved on to different types of web…

  • Integration Of Jenkins With Selenium WebDriver

    We have provided a step-by-step Guide to Setup and Configure Jenkins with Selenium: Our previous tutorial in the DevOps Series explained Ansible Roles and Integration with Jenkins in DevOps. Jenkins is an open source tool written in Java. It provides continuous delivery and continuous integration services for software development.  It…

  • Automation Testing Using Cucumber Tool and Selenium

    In the last Selenium tutorial, we introduced you to Selenium Grid, which is a distributed test execution environment to speed up the execution of a test pass. Now at the end of this comprehensive Selenium training series, we are learning advanced Selenium testing and related concepts. In this and the…

  • Selenium Tutorials

    A Complete List of the Best Selenium Tutorials to Learn and Master Selenium From Scratch:  After several frequent requests from STH readers, today we are finally launching our FREE Selenium Tutorial series. In this Selenium training series, we will cover all Selenium testing concepts and its packages with easy-to-understand practical…

  • Selenium Integration with Robot Framework

    This Tutorial explains Uses, Examples & Functionalities of Robot Class In Java and its Integration with Selenium Framework: Robot Java is a Robot class in the Java AWT package. It is generally used to simulate real-time keyboard and mouse operations which we do manually. The main purpose of the Robot Class in…

  • Selenium WebDriver Tutorial

    In the previous two tutorials, we made you acquainted with the basic architecture and features of WebDriver and the infrastructure required to get started with Selenium WebDriver. Assuming that you all might have set up the system with all the utilities and packages, we will move further with the implementation…

  • Integration of Selenium with JMeter

    Overview: Hi Testers!! In this tutorial, you will learn a very interesting topic i.e. integrating your selenium scripts with JMeter and measuring the performance. Below are the topics covered in this session: Integrating Selenium with JMeter. Using WebDriver Sampler Plugin. => Click here for The Complete Free Training On JMeter…


36 thoughts on “Cucumber Selenium Tutorial: Cucumber Java Selenium WebDriver Integration”

  1. I am test professional working on BI/ETL
    have anyone tried automation testing for BI/ETL projects if so, can you please share some perspective about automation in ETL/BI projects. i am planning to come up with strategy for performance testing for regression suite

    Reply
  2. Hi . I wan’t to get handler of diglog when click [@id=’pop’]”)).click(); show popup. But i only get handler of parent window. Please help me !!!!!!
    String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
    String subWindowHandler = null;
    System.out.println(“So1 “+parentWindowHandler);
    driver.findElement(By.xpath(“//*[@id=’pop’]”)).click();
    Set handles = driver.getWindowHandles(); // get all window handles
    Iterator iterator = handles.iterator();
    while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    System.out.println(“So2 “+subWindowHandler);
    }
    driver.switchTo().window(subWindowHandler);

    Reply
  3. Use below dependencies

    info.cukes
    cucumber-java
    1.1.5
    test

    info.cukes
    cucumber-junit
    1.1.5
    test

    junit
    junit
    4.11
    test

    import cucumber.api.java.en.Given;
    import cucumber.api.java.en.Then;
    import cucumber.api.java.en.When;

    public class stepDefinition {
    @Given(“^sample feature file is ready$”)
    public void givenStatment(){
    System.out.println(“Given statement executed successfully”);
    }
    @When(“^I run the feature file$”)
    public void whenStatement(){
    System.out.println(“When statement execueted successfully”);
    }
    @Then(“^run should be successful$”)
    public void thenStatment(){
    System.out.println(“Then statement executed successfully”);
    }
    }

    And for runner please provide feature path features=”src/test/resources”

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

    @SuppressWarnings(“deprecation”)
    @RunWith(Cucumber.class)
    @Cucumber.Options(format={“pretty”,”html:reports/test-report”}, features=”src/test/resources”,tags= “@smokeTest”)
    public class CucumberRunner {
    }

    Happy coding

    Reply
  4. sir is it supports java to work on calabash and cucumber together?????????? pls take class on that from ur side it will very useful

    Reply
  5. This is very good tutorial to start working with Selenium and it depends on individual, how efficiently use this tutorial and develop framework for his project requirements.

    Reply
  6. Hi,

    Can anyone help me out with creating cucumber test case for Testing CMP for messages in queue. i have code we need to create test case for that.

    {
    “documentType”: “Letter”,
    “deliveryType”: “COMPOSE”,
    “materialTemplateId”: “60”,
    “documentData”: {
    “contractId”: “5495739”,
    “documentTypeTxt”: “A00500SL”,
    “longDocumentTypeTxt”: “FWO LTR”,
    “documentInstanceId”: null,
    “clientInfo”: {
    “clientRelationshipCd”: “1”,
    “partyId”: “3938701”,
    “firstName”: “DIANE”,
    “lastName”: “CONROY-KELLOGG”,
    “middleName”: “B”,
    “fullName”: null,
    “phoneNumber”: null,
    “addressLine1”: “10332 S BEGOLE RD”,
    “addressLine2”: “PERRINTON MI 48871-9767”,
    “addressLine3”: null
    },

    Reply
  7. You say to create a junit runner to run the test but you dont say where to create it? What file? What folder? Where?

    Step #6: Create a Junit runner to run the test.
    1
    @RunWith(Cucumber.class)
    2
    @Cucumber.Options(format={“pretty”,”html:reports/test-report”},tags= “@smokeTest”)
    3
    public class CucumberRunner {
    4
    }

    Reply
    • U can creat runner class in src/test/java folder within the same package or creat separate PKG for runner class …..

      Reply
  8. Hi,How to implement Cucumber Using TestNG. I am implemented my project in Hybrid FrameWork[Data driver+TestNG+POM].I want to implement /convert my Project to Cucumber[BDD]. How can i achieve this.

    I understand your two classes on Cucumber.I want your suggestion to move forward.My target is convert my project toBDD.

    Reply
  9. If you found problem in using regular expression at When statement like @When(“^user logged in using username as \”(.*)\” and password as \”(.*)\”$”) just made change as follows @When (“^user logged in using username as (.*) and password as (.*)$”)

    Reply
  10. Steps aren’t clear and seem to be making assumptions of prior knowledge. Never got to run successfully if follow these steps exactly as described.

    Reply
  11. Hi,

    Can we use @test, @before junit annotations along with cucumber annotations like @given etc

    for example, can we write like below? if so, how will be the junit report? pls reply.

    @Given(“^user is on homepage$”)
    @before
    public void launchhomepage()
    {
    driver.get(“homepageurl”);
    }

    @When(“^user enters username and password$”)
    @And(“^user clicks login button$”)
    @test
    public void doLogin()
    {
    driver.findElements(By.id(“usr”).sendKeys(“user1”);
    driver.findElements(By.id(“pwd”).sendKeys(“pwd”);
    driver.findElements(By.id(“submit”).click();
    }

    Reply
  12. I have the same question as Charlie and minnu kumari, i.e. where do we put the runner class ? Is Junit a dependency for Cucmuber ? Or will it run without Junit ?

    Reply
  13. Cannot Run the programs. facing below issues

    1. sample.feature File Warning “Step does not have a matching glue code”

    2. “No tests found with Test runner Junit 4.”

    Reply
  14. @Syed yes u can create multiple scenarios in one feature file.
    User Background for common set of pre-conditions.
    User multiple scenarios – when then conditions in one feature file.

    Reply
  15. Hi Charles, you can create a new Junit test case inside the src/test/java with below code & run as Junit test

    import org.junit.runner.RunWith;
    import cucumber.junit.Cucumber;
    import cucumber.junit.Cucumber.Options;

    @RunWith(Cucumber.class)
    @Options(format={“pretty”,”html:reports/test-report”},features = “Feature\\seleniumsample.feature”)
    public class CucumberRunner
    {

    }

    Reply
  16. sir i have tried same code that you are given but when i execute that it throws an error as follows

    cucumber.runtime.CucumberException: No features found at [com/cucumber/test] at cucumber.runtime.model.CucumberFeature.load(CucumberFeature.java:47)
    at cucumber.runtime.RuntimeOptions.cucumberFeatures(RuntimeOptions.java:82)
    at cucumber.junit.Cucumber.(Cucumber.java:60)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

    tting fail gives error

    Reply
  17. Thank you so much for taking your personal time and effort to write this tutorial. It’s indeed absolutely useful for those starting in the Cucumber/SeleniumWebDriver world. Much appreciated.

    Reply
  18. Hi,
    I am new to cucumber and started exploring on it.
    May i know how do we link the feature file with selenium script and types of regex to use the step definitions?

    Thanks in advance!!!

    Reply
  19. In Junit runner, we should give @CucumberOptions, @Cucumber.Options is not working….

    @CucumberOptions(
    format={“pretty”,”html:reports/test-report”},
    features=”src/test/resources”,
    tags= “@smokeTest”)

    Reply
  20. HI , Thanks for the valuable efforts you put.Excellent work.
    Every time when i execute this script new report is overridden on to old one. So what is the source code to see all the reports instead of single one.
    awaiting your reply!!!!!
    Thanks 🙂

    Reply

Leave a Comment