Sunday, October 2, 2016

Cucumber Framework - Selenium WebDriver with Java and Maven

Cucumber and Selenium WebDriver with Java and Maven

                                                    

                                                     Cucumber Basics - PART I

 

                                                      Cucumber Basics - PART II

 

 

 

Cucumber, the buzz word in Automation testing. Here is the post on Cucumber and Selenium WebDriver implementation with Java to automate Web Application.

This post includes basic cucumber configuration framework. Someone interested in learning cucumber framework basics and implement in project can go through. 

Implemented the cucumber framework automation in this post taking Gmail login as example

INTRODUCTION:
Cucumber and Selenium WebDriver with Java is powerful combination with respect to Web Application automation. Cucumber is easy to learn and implement. Cucumber allow to write the test cases in format which is very similar to English understandable format, written by using language 'Gherkin'. Because of its easy implementation, language usage which is near to common English language and Selenium WebDriver combination which allow to run the same code on multiple browsers and different platform, combination of Cucumber and SeleniumWebDriver with java is more famous. 

BASICS:
Cucumber has three important sections feature file, step Definition and Runner Class. Whole system run based on these files. Along with this, for this post created the Project using Maven which runs based on dependencies added in the pom.xml

PROCESS OVERVIEW:
Cucumber execution process depends on above mentioned 3 files. Lets address them in brief

feature file: Feature file is like normal text file however extension should be as .feature. The language used in writing the feature file is Gherkin. feature file is referred by Stake holders, Business Analysts, Developers and also Testers. feature file contains the Scenarios, which are based on the User Stories. It need to use few specific keywords of Gherkin. First line of feature file should start with the Feature, followed by Scenario. There can be multiple Scenarios in the Feature file. Each Scenario can be complete using Given, When, Then, And, But.

Sample feature file

Feature: Gmail Testing

Scenario: Gmail Login
Given gmail url opened
Then fill the user id
And fill the password
Then click on Login

Scenario: Compose Email
Given user logged in
Then click on Compose button
And fill the to subject content
Then click on Send

Scenario: Gmail logout
Given user logged in
When logout button visible
Then click on logout

stepDefinition: Once completed with writing scenario, as mentioned above, next step is to move ahead with writing the methods / functions for the scenarios mentioned in feature file. Typically, this section contains the actual login implementation for automation. Language would be based on the once choose for automation. Say like java, ruby, python and more. As part of this post, Java is language used and project created as Maven Project.

RunnerClass: In simple terms, this can be referred as main class in typical java program from where the execution starts. In Cucumber, the execution starts from the RunnerClass. 

Along with these 3 section, when project created as Maven, one more important section is about POM.xml, all the dependencies of the project would be added in the POX.xml file. Dependencies are just like jar files references. Instead of typical way of downloading the jars and assigning to the project, would add dependencies of the jars into the POM.xml

Basic dependencies which are required for Cucumber framework
  1. Maven dependency for JUNIT
  2. Maven dependency for Selenium-Java  (Selenium WebDriver)
  3. Maven dependency for Cucumber-core
  4. Maven dependency for Cucumber-java
  5. Maven dependency for Cucumber-junit
 NOW THAT WE HAVE ENOUGH CONTENT ON CUCUMBER, LETS IMPLEMENT

As part of this post, we would be automation gmail login using Cucumber Framework

 PREREQUISITES:
  1. Java JDK (link to download java)
  2. Eclipse IDE, preferably Luna (link to download Eclipse Luna)
  3. Firefox browser preferably version 46.0
  4. Firebug and Firepath Addins (Please contact me for more information)
  5. geckodriver.exe if using Selenium-Java webdriver version 3.0 or higher (link to download geckodriver)

Once all the above download are completed, lets move ahead with the steps

STEP 1: Configure Maven in Eclipse
Open Eclipse and Click on Help --> Eclipse Marketplace


 In the search field, search with text maven and select m2e the click install and complete installation


STEP 2: Configure Cucumber in Eclipse
Click on Help --> Install New Software
In the Search field, search for url http://cucumber.github.com/cucumber-eclipse/update-site
and click on Enter. Select the checkbox Cucumber Eclipse Plugin and install



STEP 3: Create Maven Project
Click on File --> New --> Project
Select Maven --> Maven Project option and click on Next as shown below
 
 In the New Maven project window keep default selection and click Next





In the New Maven project, Select an Archetype, keep default selection and click Next


In the below screen fill group Id, artifact id and Package name
artifact id is project name



Maven project created successfully.
In the project folder Icon, text M displayed which represents project is maven project


Next step is to understand the folders in the Project
src/test/java is the folder where stepDefinition, RunnerClass and Feature file have to be written
pom.xml is where need to add dependencies

Adding dependencies in pom.xml

Open pom.xml file and click on the tab pom.xml as shown below
 

Below is default pom.xml with dependencies added

 

NOTE: Default created with JUnit dependency with version 3.8.1, however all dependencies update with the latest versions

HOW TO SEARCH FOR DEPENDENCY AND ADD

 Need to add below dependencies
1) JUnit - update to latest one
2) Selenium java
3) Cucumber Core
4) Cucumber Java
5) Cucumber JUnit

Open https://mvnrepository.com/ and search for dependencies as below


 

Click on the link and copy dependency, paste in the pom.xml in between tags
<dependencies>
</dependencies>
 

 

Update dependency as shown below
 

Similarly for all remaining. However have added the dependencies here. So can use below ones

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.0-beta4</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>1.2.5</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>

 STEP 4: Create feature file
As mentioned in earlier steps, all the automation should be done in folder src/test/java
So create a file in folder. Right click on  src/test/java and click New --> Other, select FILE as shown below
Give the file name (file name can be anything) and extension SHOULD BE .feature

 

 

Feature file would be displayed under src/test/java and Icon would be displayed because we have installed Cucumber Eclipse Plugin. When file opened, default template would be displayed with information. Can keep the same and modify or delete it and start new. Lets delete and start new



Lets write feature file for our testing on gmail, which we have already discussed as above


After file is saved, gets warning with methods not implemented, because we have not written the code for these scenarios in stepDefinition

 

feature file text for you to copy into your file

Feature: Gmail Testing
Scenario: Gmail Login
Given url opened
Then enter user id and click next
Then enter password
And click login

Scenario: Gmail Close
Then Close browser

Step 5: CREATE STEP DEFINITION class in src/test/java --> gmailLogin.GmailTesting package in this post
As mentioned earlier, for each line in feature file with keywords Given, Then, When, And, But the respective method/function should be available in the stepDefinition file with few rules as shown

For example
feature file
Given url opened

stepDefinition
public class stepDefinition 
{

     @Given("^url opened$")
     public void url_opened()
    {
         //Actual code for the url open 
    }
}


Note1: feature file line and annotation content in stepDefinition should be same, however method / function name is optional. Good practice is to have same name and keep _ (underscore) and method names are not encourages with spacce in between words.
In this example it is
Given url opened
@Given("^url opened$")
followed by function

Similarly for remaining lines. However this would be challenging to write all the methods / function names in step definition. So one smart way of doing is, run the feature file with no methods and would throw the message saying methods with respective definition not found, which can be copied into the stepDefinition and then implement actual coding for automation.

Please follow steps as below
In the feature file, right click and select Run as -- > Cucumber Feature. Displays the message saying functions are missed, copy those and paste in the stepDefinition file as shown below





 


After pasted in stepDefinition file, import or type Ctrl+Shift+O to import all automatically to class


Note: From the methods, remove the comments and throw new PendingException() and throws Throwable. While really using in method, can import or add them

 

Start writing the code in respective methods as shown below

Note: As we are using Selenium WebDriver version 3.0, need to include geckodriver as mentioned in script, so as to launch Firefox browser. To know more information on 3.0 version and geckodriver, will be posted in another blog

Here is the code for stepDefinition

package gmailLogin.GmailTesting;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

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

public class stepDefinition {
   
    public static WebDriver obj=null;
   
    @Given("^url opened$")
    public void url_opened() {
        System.setProperty("webdriver.gecko.driver",
                "D:\\geckodriver.exe");
        obj=new FirefoxDriver();
        obj.manage().window().maximize();
        obj.get("https://mail.google.com");
    }

    @Then("^enter user id and click next$")
    public void enter_user_id_and_click_next() throws InterruptedException  {
        obj.findElement(By.id("Email")).sendKeys("YOURUSERID");
        obj.findElement(By.id("next")).click();
        Thread.sleep(2000);
    }

    @Then("^enter password$")
    public void enter_password()  {
        obj.findElement(By.id("Passwd")).sendKeys("YOURPASSWORD");
    }

    @Then("^click login$")
    public void click_login() throws InterruptedException  {
        obj.findElement(By.id("signIn")).click();
        Thread.sleep(6000);
    }

    @Then("^Close browser$")
    public void close_browser() {
        obj.quit();
    }
}

STEP 6: Create RunnerClass

 

@RunWith(Cucumber.class) - Execute the class and run with Cucumber class

@CucumberOptions(
                             features="src/test/java/demo.feature",
                             format={"pretty","html:target/Reports"}
         )

features - path of the feature file
format - generate pretty format html report under target folder with the results folder name as Reports

 

CODE for RunnerClass

package gmailLogin.GmailTesting;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features="src/test/java/demo.feature",
        format={"pretty","html:target/Reports"}
        )
public class RunnerClass {

}


Execute the script from RunnerClass, by selecting Run as JUnit and verify the results


 

1) Verify in Console
 

2) Verify in target folder -- >Reports folder to verify results in html format. IF running for first time, need to refresh the project to display the Reports folder under target folder

 

Navigate to project workspace location to view the html results

To know workspace location right click Project and click on Properties and verify path as below











HTML Results









 THAT IS IT. 

CUCUMBER BASIC PROGRAMMING CAN BE IMPLEMENTED USING THE ABOVE STEPS


HAPPY LEARNING!!!