Step by step tutorial to integrate cucumber with selenium by Maven

Configure Maven

Go to CMD and give this command:
mvn --version

If you get an error as:
mvn’ is not recognized as an internal or external command

Then you must have to configure maven

Download maven Binary zip archive from here and extract to “C:\>Program Files > Java” (For windows user)

Now go to System Environment Variables and set Variable as MAVEN_HOME and value as C:\Program Files\Java\apache-maven-3.8.1

And add bin Path

Ok and Apply changes

Now go to cmd and give the command:

mvn --version

Now it will show you version without any error

Cucumber integration with selenium

Generate Step Definitions

Open intellij

Go to File > New > Project

Select Maven and Click Next

Give Project name and click Finish

This is the project outline.

Configure defender automatically if interrupted

Add following dependencies to your pom.xml file

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-remote-driver -->

    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-firefox-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.141.59</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.141.59</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>2.3.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>2.3.1</version>
        <scope>test</scope>
    </dependency>

</dependencies>

Click here to import packages

Now create a new directory named resources under test folder

Right click to the resources folder and set Mark Directory as
Test Resources Root

Create a file named login.feature under the resources folder

If Intellij prompt to install gherkin package, install it

Write following contents in login.feature file

Feature: Login to an e-commerce website

  Scenario: Verify users can login to portal with valid credentials
    Given User visits e-commerce website
    When User enters valid credentials
    Then User can logged in successfully

Now create a java class named RunCucumberTest under java folder

Write following code in RunCucumberTest file:

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

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty"})
public class RunCucumberTest {
}

Now select the RunCucumberTest class and right-click to Run cucumber test

You will get following result in console

They are the basically step definitions that will be used to write our BDD code. This is showing PendingException because we do not have StepDefinitions yet.

Write code to Step Definitions

Now create a class named StepDefinitions under java folder

Copy-paste the following code we just generated. Remove
throw new PendingException(); As this is no longer needed

@Given("^User visits e-commerce website$")
    public void user_visits_e_commerce_website() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @When("^User enters valid credentials$")
    public void user_enters_valid_credentials() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

    @Then("^User can logged in successfully$")
    public void user_can_logged_in_successfully() throws Exception {
        // Write code here that turns the phrase above into concrete actions
    }

Now download geckodriver-v0.29.1-win64.zip and keep it to the resources folder

This is used to drive the firefox browser. You can also download chromedriver and keep it in the resources folder

Now add this 2 line code inside StepDefinitions class file

public WebDriver driver;
    WebDriverWait wait;

Now write this code to @Given Step Defs

@Given("^User visits e-commerce website$")
    public void user_visits_e_commerce_website() throws Exception {
        System.setProperty("webdriver.gecko.driver", "./src/test/resources/geckodriver.exe");
        FirefoxOptions ops=new FirefoxOptions();
        ops.addArguments("--headed"); //uncomment if you want to run in headless mode
        driver = new FirefoxDriver(ops);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://automationpractice.com");

    }

So, the code view will be

Now add this code to @When Step Defs

@When("^User enters valid credentials$")
    public void user_enters_valid_credentials() throws Exception {
        wait.until(ExpectedConditions.presenceOfElementLocated (By.className("login")));// wait until getting the login button
        WebElement btnLogin=driver.findElement(By.className("login"));
        btnLogin.click();
        Thread.sleep(1000);
        WebElement txtEmail=driver.findElement(By.id("email"));
        txtEmail.sendKeys("testuser412@grr.la");
        WebElement txtPassword=driver.findElement(By.id("passwd"));
        txtPassword.sendKeys("2t8zmqzL");
        Thread.sleep(1000);
        WebElement btnSubmitLogin=driver.findElement(By.id("SubmitLogin"));
        btnSubmitLogin.click();
    }

And finally, add this code to @Then Step Defs

@Then("^User can logged in successfully$")
    public void user_can_logged_in_successfully() throws Exception {
        WebElement lblUserName=driver.findElement(By.xpath("//span[contains(text(),'Test User')]"));
        Assert.assertEquals(lblUserName.getText(),"Test User");
    }
@After
    public void closeBrowser(){
        driver.quit();
    }

So, the full StepDefinitions.java file will be:

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class StepDefinitions {
    public WebDriver driver;
    WebDriverWait wait;
    @Given("^User visits e-commerce website$")
    public void user_visits_e_commerce_website() throws Exception {
        System.setProperty("webdriver.gecko.driver", "./src/test/resources/geckodriver.exe");
        FirefoxOptions ops=new FirefoxOptions();
        ops.addArguments("--headed"); //uncomment if you want to run in headless mode
        driver = new FirefoxDriver(ops);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://automationpractice.com");
    }

    @When("^User enters valid credentials$")
    public void user_enters_valid_credentials() throws Exception {
        WebDriverWait wait=new WebDriverWait(driver,30);
        wait.until(ExpectedConditions.visibilityOfElementLocated (By.className("login"))).isDisplayed();
        WebElement btnLogin=driver.findElement(By.className("login"));
        btnLogin.click();
        Thread.sleep(1000);
        WebElement txtEmail=driver.findElement(By.id("email"));
        txtEmail.sendKeys("testuser412@grr.la");
        WebElement txtPassword=driver.findElement(By.id("passwd"));
        txtPassword.sendKeys("2t8zmqzL");
        Thread.sleep(1000);
        WebElement btnSubmitLogin=driver.findElement(By.id("SubmitLogin"));
        btnSubmitLogin.click();
    }

    @Then("^User can logged in successfully$")
    public void user_can_logged_in_successfully() throws Exception {
        WebElement lblUserName=driver.findElement(By.xpath("//span[contains(text(),'Test User')]"));
        Assert.assertEquals(lblUserName.getText(),"Test User");
       
    }
@After
    public void closeBrowser(){
        driver.quit();
    }
}

Now run the project and you will see that automation happened and test passed

Convert to POM

Create a folder named pages under java folder. Then create a java class named Login.java under the pages folder

Now write following code under the Login.java file

package pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class Login {
    @FindBy(className="login")
    WebElement linkLogin;
    WebDriver driver;
    @FindBy(id="email")
    WebElement txtEmail;
    @FindBy(id="passwd")
    WebElement txtPassword;
    @FindBy(id="SubmitLogin")
    WebElement btnSubmitLogin;
    public Login(WebDriver driver)
    {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }
    public void doLogin(String email,String password) throws InterruptedException {
        linkLogin.click();
        Thread.sleep(1000);
        txtEmail.sendKeys(email);
        txtPassword.sendKeys(password);
        Thread.sleep(1000);
        btnSubmitLogin.click();

    }
}

Now go to StepDefinitions file

Edit the @When Step Defs block

@When("^User enters valid credentials$")
    public void user_enters_valid_credentials() throws Exception {
 wait=new WebDriverWait(driver,30);
        wait.until(ExpectedConditions.presenceOfElementLocated (By.className("login"))); // wait until getting the login button
        Login login=new Login(driver);
        login.doLogin("testuser412@grr.la","2t8zmqzL");
    }

Now run the project and still you will find the project runs smoothly

Parameterized cucumber integration with selenium

Go to login.feature file and update by the following context:

Feature: Login to an e-commerce website

  Scenario Outline: Verify users can login to portal with valid credentials
    Given User visits e-commerce website
    When User enters valid "<username>" and "<password>"
    Then User can logged in successfully

    Examples:
      | username           | password |
      | testuser412@grr.la | 2t8zmqzL |

Then go to StepDefinitions file and update @When Step Defs block

@When("^User enters valid \"([^\"]*)\" and \"([^\"]*)\"$")
    public void user_enters_valid_credentials(String username, String password) throws Exception {
 wait=new WebDriverWait(driver,40);
        wait.until(ExpectedConditions.presenceOfElementLocated (By.className("login"))); // wait until getting the login button
        Login login=new Login(driver);
        login.doLogin(username,password);
    }

Now run the project again and the project will run smoothly

Report Generate

Now we will generate report

Go to pom.xml and add the following code

<build>
        <plugins>
            <plugin>
                <groupId>net.masterthought</groupId>
                <artifactId>maven-cucumber-reporting</artifactId>
                <version>5.3.0</version>
                <executions>
                    <execution>
                        <id>execution</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <projectName>Sample-Cucumber-TestNG</projectName>
                            <skip>false</skip>
                            <outputDirectory>reports/html-reports</outputDirectory>
                            <inputDirectory>target/cucumber-reports</inputDirectory>
                            <jsonFiles>
                                <param>**/*.json</param>
                            </jsonFiles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Must import by clicking maven import icon

Now go to RunCucumberTest file and add html:target and json:target under @CucumberOptions

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

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"pretty","html:target/cucumber-reports/cucumber.html",
        "json:target/cucumber-reports/cucumber.json"})
public class RunCucumberTest {
}

Now go to terminal and hit following command:

mvn clean install

This will generate html report under reports Folder

Now right-click on any report and click on Show in Explorer
Then open a report

Here is the full project:
https://github.com/salmansrabon/java-cucumber-selenium-demo

about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *