Objective

Now a days lot of companies are asking for knowledge of BDD and exposure or experience in Behat/Cucumber.

Don’t be too worried about Cucumber. Cucumber is nothing but Steps written in Gherkin language to which we have to map corresponding code.

What we will be using:

  • IntelliJ IDE – My favorite
  • Cucumber plugin
  • Gherkin plugin
  • TestNG
  • and of course JAVA

Installing Plugins

Go to File > Settings > Plugins in InteliJ and install “Cucumber for Java” and “Gherkin”.

Cucumber for Java will enable us to create cucumber related files and Gherkin in the supported language for the same.

Maven Configuration

Configure your pom.xml with following dependencies.

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>1.2.5</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.10</version>
            <scope>test</scope>
        </dependency>

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.2.0</version>
        </dependency>

Always ensure that you are using latest versions for the dependencies.

SeleniumTest.java

First and foremost, lets write a simple Selenium test.  This is the easiest way of making the cucumber provide you half of the pre-written code or much easier if you have an already written code.

Create a package “tests” in src/test/java directory and add SeleniumTest.java class file to it.

Below simple test is to open linkedin.com and do the login.

package tests;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

public class SeleniumTest {

    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver","D:\\Selenium Webdriver/chromedriver.exe");
        driver = new ChromeDriver();

        driver.get("http://www.linkedin.com");

        driver.findElement(By.id("login-email")).sendKeys("yourusername");

        driver.findElement(By.id("login-password")).sendKeys("yourpassword");

        driver.findElement(By.id("login-submit")).click();

        String username = driver.findElement(By.xpath(".//*[@id='voyager-feed']/div[2]/aside[1]/div/div/div/div[1]/a[2]")).getText();

        Assert.assertEquals(username, "Ashish Deshmukh");//Replace with your profile name

        driver.quit();

    }
}

Above we are doing a simple login on Linkedin and verifying the username in the side panel.

Login_Test.feature

Here begins the first cucumber file. The extension of cucumber file is “.feature”. It contains your steps and scenarios.

Create a package “features” in src/test/java directory and add “Login_Test.feature” file to it.

Paste the following code in Login_Test.feature file.

Feature: Login Action

  Scenario: Successful Login with Valid Credentials
    Given User is on Home Page
    When User enters UserName
    And User enters Password
    Then User is logged in successfully

Here

  • Feature defines what feature we are going to test
  • Scenario is obviously the scenario defination
  • Given acts as pre-requisit
  • When is the condition along with And operator
  • Then is our expected outcome

This is how basically you define cucumber’s gherkin language. There are more available keywords, but not relevant in this setup tutorial.

TestRunner.java

Till now, we have written a selenium test and created a cucumber feature file. Keep in mind that we still cannot execute the cucumber test. For that we need to create a runner java class.

Create “TestRunner.java” in “tests” package which we created previously to store “SeleniumTest.java” file.

Add following code to it.

package tests;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.*;

@CucumberOptions(features = {"src/test/java/features"},glue={"stepDefinition"})

public class TestRunner extends AbstractTestNGCucumberTests{

}

In above code, we have specified the location of our feature files i.e. “src/test/java/features”.

Also note that we have mentioned “glue={stepDefinition}”. This is nothing but the location of step definitions which we will be adding next for our feature file.

Note that this java class enables the Run option. So lets just run it.

You’ll notice that test runs successfully with following text in console:


1 Scenarios (1 undefined)
4 Steps (4 undefined)
0m0.000s

You can implement missing steps with the snippets below:

@Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^User enters UserName$")
public void user_enters_UserName() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^User enters Password$")
public void user_enters_Password() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^User is logged in successfully$")
public void user_is_logged_in_successfully() throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

Now all we have to do is copy paste the above step definitions in a step definition file.

Test_Steps.java (Step Definition file)

Lets create a stepdefinition file for our cucumber now.

Create a package “stepDefinition” in “src/test/java” and add Test_Steps.java class to it.

Note that package name is same what we defined as “glue” in our TestRunner.java class.

Copy above output in the class (and remember to remove the “throw new PendingException”)

Your class file will look as below.

package stepDefinition;

import cucumber.api.PendingException;
import cucumber.api.java.en.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;

public class Test_Steps {
    public static WebDriver driver;
    @Given("^User is on Home Page$")
    public void user_is_on_Home_Page(){
        // Write code here that turns the phrase above into concrete actions
        System.setProperty("webdriver.chrome.driver","D:\\Selenium Webdriver/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.linkedin.com");
    }

    @When("^User enters UserName$")
    public void user_enters_UserName() throws Throwable {
        // Write code here that turns the phrase above into concrete actions
        driver.findElement(By.id("login-email")).sendKeys("username");
    }

    @When("^User enters Password$")
    public void user_enters_Password() {
        // Write code here that turns the phrase above into concrete actions
        driver.findElement(By.id("login-password")).sendKeys("password");
        driver.findElement(By.id("login-submit")).click();
    }

    @Then("^User is logged in successfully$")
    public void user_is_logged_in_successfully() {
        // Write code here that turns the phrase above into concrete actions
        String username = driver.findElement(By.xpath(".//*[@id='voyager-feed']/div[2]/aside[1]/div/div/div/div[1]/a[2]")).getText();

        Assert.assertEquals(username, "Ashish Deshmukh");
        driver.quit();
    }
}

We have simply added the code from SeleniumTest.java file into the steps. Now SeleniumTest.java is redundant to us.

Now Run “TestRunner.java” again and you’ll see that our test starts executing on chrome browser.

Final Project structure is as below.

cucumber

Advertisements

One thought on “Cucumber Setup – TestNG – Selenium

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s