Continous Integration and Delivery Model

High Level brief idea about CI CD

Normal Development and Develivery cycle happens:

Unit Test > Platform Test > Delivery to Staging> Application Acceptance tests> Deploy to Production > Post deploy tests

In CI and CD model process of delivering software updates to users on a nearly content basis.Continues_deployment.png

Continuous Development – As soon as development done in local branch it should debug and unit tests and Code review automatically

Continuous Integration – Constant integration of changes to app at all stages of the delivery chain

Continuous delivery – Marge all branch tested code by CI server automatically delivery to QA/Staging server

Similar production  deployment is marging of test deployment and deploy to main branch. It will continuously automated Tests on different environment and Devices and deploy on the Production/App Store/Play Store.

Posted in CI and CD, Uncategorized | Tagged | Leave a comment

Java Inheritance

Learn from my YouTube Video – Java Inheritance

Also learn how to setup selenium and write first program

  • In simple term inheritance is nothing but parent-child relationship to accessing once class members into another class.

First to understand Static and Non-Static Class Member and How to access Static and Non-Static class members (Variables and Methods)


Example:

public class Class1 {

      //Static member

      static int a=10, b=20;

      //Non-Static member

      int c=30, d=10;

      //Create Static member with retuning value

      public static int sum(int a, int b)      {

         int result = a+b;

         return result;

      }

      //Create Static member without returning value

      public static void mul (int a, int b){

            System.out.println(a*b);

      }

      //Create Non-Static member with retuning value

      public int add2(int c, int d){

            int result = c + d;

            return result;

      }

      public static void main(String [] args)  {

       //Access Static Class variable and methods

     int x = Class1.sum(a, b);

     System.out.println("Result : " +x); //Result : 30

       Class1.mul(a, b); //Result : 200 OR

       mul(a,b);

       // Access Non Static Class variable and methods

        // add2(c,d); // Can't allowed to access Non Static Class member

       Class1 obj = new Class1();

       System.out.println(obj.add2(obj.c, obj.d));

      }

 }

Result : 30
200
200
40

Three leval of Inheritance in Java

  1. Single inheritance

Ex. public class A extends B (Parent-Child concept)

single_inheri

2. Multi-Level Inheritance

Ex. public class B extends A

public class C extends B

multi-level

Q – If class A and B having same class members the how class C consider?

A – First priority goes to same class than immediate parent and last on Grand Parent

3. Multiple Inheritance

Note – Java does support multiple inheritance due to diamond problem

Ex. public class C extends A, B

multi-level_001

Inheritance:

  • Inheriting the class members (Variables and Methods) from one class to another.
  • Important term
    • Super Class/Parent Class/Base Class – The class which is inheriting into other class means reusing variables and method of this class
    • Sub Class/Child Class/Derived Class – The class which is inherited Parent class in order reuse the variable and method of Parent class
  • Using ‘extends’ keyword inheritance possible between Super and Sub class
  • A subclass inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.

class subclass-name extends superclass-name
{
// Body of the class
}

Example :

public class A { 
 // Here A is Parent/Super/Base Class
 
 int a = 10;
 int b = 20;

public void display(){ 
 System.out.println("This is the display method of Class A");
 } 
 public static void main(String[] args) {
 
 A obj = new A();
 System.out.println("Print a :"+obj.a); //Accessing non-static variable of same class
 System.out.println("Print b :"+obj.b); 
 obj.display(); //Accessing non-static method of same class
 }
}
public class B extends A{
 // Here B is Child Class of Parent A
// int a = 30;
 int b = 40;
 
 public void display(){ 
 System.out.println("This is the display method of Class B");
 super.display(); // Accessing non-static method of Parent Class A
 }
 public static void main(String[] args) {
 
 B objB = new B();
 System.out.println("Print Class B variable a :"+objB.a); // Accessing non-static variable of same Class A
 System.out.println("Print Class B variable b :"+objB.b); // Accessing non-static variable of same Class B
 objB.display(); // Accessing non-static method of same class B
 
 }
}
public class C extends B{ //Multi-level inheritance

// Here C is Sub-sub class of Grand Parent A
 // B is Parent Class of Class C
 // B is Sub Child Class of Class A
 public static void main(String[] args) {
 C objC = new C();
 System.out.println("Print Class A variable a :"+objC.a); //Accessing non-static variable of Grand Parent A
 objC.display(); //Accessing non-static method of Parent B
 }

}

Output of Class C Result :

Print Class B variable a :10
This is the display method of Class B
This is the display method of Class A

 

Posted in Java | Leave a comment

Install TestNG in Eclipse

What is TestNG, Install and Execute the script – http://www.guru99.com/all-about-testng-and-selenium.html

Install from Marketplace

  • Open marketplace window from Help > Eclipse Market Place
  • Find by keyword testing and search
  • Install it

Install as New Software in IDE

  1. Launch the Eclipse IDE and from Help menu, click “Install New Softwaretestng1_001
  2. You will see a dialog window, click “Add” button

testng_2

3.Type name as you wish, lets take “TestNG” and type “http://beust.com/eclipse/” as location. Click OK.

testng_3

4. Select TestNG Latest Version Ex. 6.9.12.xxxx

testng_4

5. Click “I accept the terms of the license agreement” then clickFinish.

TestNG_5.png

6. It downloading software and installation being in process

testng_5_1

7. You may or may not encounter a Security warning, if in case you do just clickOK.

testng_68. ClickNext again on the succeeding dialog box until it prompts you to Restart the Eclipse.

testng_7

9. Verify TestNG installed or not in the eclipse from Window > Preferences > TestNG

10. In the project include the TestNG Reference jar library files on clicking suggesting help ‘Add TestNG Library’

testng_8

11. Import references in the Class for TestNG annotation ex. @Test

testng_10

Verify Reference library added in Package Explorer

testng_9

Or Add TestNG into Java Build Path

Add_TestNG_BuildPath.png

Or Add TestNG into Java Build Path

 

Posted in TestNG, Uncategorized | Leave a comment

Selenium 3.0

Refer youtube video – First Program in Selenium 3.0

  1. Explain Selenium 1.0 and RC and how it works
  2. Explain Selenium 2.0
  3. Explain changes in Selenium 3.0
  4. Setup 3.0 environment and Demo

Selenium 1.0

I would like to start with Selenium 1.0 it will help to understand what are the changes are in 3.0.

Selenium 1.0 introduced in 2004. JavaScript approach followed interactive with browsers using java script send box

Selenium 1.0 came with IDE with firefox plugin. This IDE itself is a framework. It has playback recording tool option to execute the test cases and test suite.

Apart from IDE there is also RC it support execution on local or remote machine with different language binding because selenium IDE scripts are written in plan html table format it just plain text file wharves RC support different programming language Java, C#, Python, Ruby

The way selenium RC works is from it has client library from different languages as mention here and from client library send command to RC , RC received the commands and send commends to browser so basically perform proxy injection of JavaScript interact with browser. RC support different OS. Logic is interactive with Dom of the browser of it support any browser similar approach.

RC receives commands from the test program, interprets them, report back the results of those tests to the test program.  RC consist of Selenium core,  that is inject into the browser using client library API when the test program opens the browser. Selenium core interprets the commands coming from the test program and execute selenese commands using browsers built-in JavaScript engine.

selenium-rc

Selenium 2.0 WebDriver

There was W3c standard taking about same-origin policy

What is Same-Origin policy ?

A web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page’s DOM.

Example – Accessing one page http://www.example.com/dir/page2.html and another page http://www.example.com/dir2/other.html allow because both Same protocol, host and port.

But if u accessing http://www.example.com:81/dir/other.html does not allow because same protocol and host but different port

So in case of Selenium RC server run locally and when local server inject proxy into the application domin so application domin is different from where RC interactive so its violating same-origin policy.

Introduce web driver 2007 for web testing tool. Unlike RC, Web driver is not relaying on java script but actually using the browser driver to interact directly with application. So it interacting natively to application injecting or communicating with DOM. Initially web drive only support JAVA.

Every browser impose very strict security rules on the JavaScript being executed to protect the users from malicious scripts. This make testing harder for some scenarios. For example IE JavaScript security model don’t allow to change the value of the INPUT file element for uploading the file and navigating between different domains

So here browser driver implantation provided top to web driver so this way it is fully supporting same-origin policy.

Webdriver and Selenium is merged in 2009. So webdriver is also supporting different browsers

At that time many scripts is written in RC so solution provided Webdriver backed selenium.  So using this interface migrate instillation of browser so that selenium core logic change the webdriver.

Selenium 3.0

Major Changes

  • From selenium webdriver API the legacy-rc library is separated. The original RC APIs are only available via the leg-rc package. So RC approach is totally dropped in 3.0
  • Selenium-Java library contains clear version of WebDriver
  • Selenium 3.0 works only with Java 1.8 or Higher
  • Support for Firefox is via Mozilla’s geckodriver.
  • Official support for IE requires version 9 or above.
  • Unused command line arguments are now no longer parsed.

Impact of Existing Scripts of Selenium 2.0 – There was no major impact of selenium 2.0 scripts just need to change the JDK version and few references.

You will get below exeption if launch firefox browser with Selenium 3 without gecko driver

Exception “java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property;”

What is Geckodriver ?

A Proxy for using W3C WebDriver-compatible clients to interact with Gecko-based browsers. Geckodriver provides HTTP API described by the WebDriver protocol to communicate with Gecko browsers, such as Firefox (Version after 47)

Selenium 3 expects you to set path to the driver executable by the ‘webdriver.gecko.driver’.

 When using Selenium 3 beta releases, you have to download geckodriver. Just like the other drivers available to Selenium,

Geckodriver download link – https://github.com/mozilla/geckodriver/releases

Now let us see the example to launch firefox browser with Selenium 3 with gecko driver

public class Test1 {

public static void main(String[] args) {

System.setProperty(“webdriver.gecko.driver”, driverPath+”geckodriver.exe”);      driver = new FirefoxDriver();        driver.quit();      }}

With Chrome driver

public class Test2 {

public static void main(String[] args) {

System.setProperty(“webdriver.chrome.driver”, driverPath+”chromedriver.exe”);      driver = new ChromeDriver();        driver.quit();      }}

Limitation of gecko driver in Firefox

If used driver.quite() and try to close the firefox driver getting exception

Solution – use driver.close()

Gecho_Driver_FF_Error.png

 

Posted in Selenium, Test Automation | Leave a comment

Deal with Web Elements and Locators to automate by selenium

Refer Youtube video for quick reference – Indetify the Web Elements and Locators – Part 1Indetify the Web Elements and Locators – Part 2

What is Web Element

  • HTML documents are made up by HTML elements. HTML elements are written with a start tag, with an end tag, with the content in between: <tagname> content </tagname>
  • WebElement represents an HTML element.

<html><body>

<strong>First name:</strong>            <input type=”text” name=”firstname”>

<strong>Last name:</strong><input type=”text” name=”lastname”>

</body></html>

  • So, here First Name and Last Name Text box are Web Elements of Web Page.In selenium we can find the web element by their html locator type.
  • Locators are the HTML properties and it address that identifies a web element uniquely within the web page
  • Here we can find the first and last name by locator type “name” and their value “firstname” and “lastname”

Most common web elements are present on the Web Page

  • Text box
  • Button
  • Link Text
  • Check box
  • Radio button
  • Drop down box
  • List box
  • Web Table(Html table)
  • Frame
  • File
  • Image, Image Link, Image button

Most common locator type

Locator

Locating elements in WebDriver is identify by using the findElement(By.locator())The findElement methods take a locator or query object called ‘By’.

1. Text box

Find “Text box” element by locator type ‘id, name’

  • Step 1: Launch the web browser (Firefox) and navigate to – https://accounts.google.com/
  • Step 2: Open firebug (either by pressing F12 or via tools).
  • Step 3: Click on the inspect icon on text box to identify the web element.
  • Selenium code – driver.findElement(By.id(“Email”))
    • Finding “Text box” element by locator ‘name’

    Selenium code – driver.findElement(By.name(“Email”))

  • Most common operations perform on Text box (Edit Box)
    • Clear – driver.findElement(By.id(“Email”)).clear()
    • Enter Text value – driver.findElement(By.id(“Email”)).sendKeys(“Test”)
    • Element display or not – Boolean status = findElement(By.id(“Email”)).isdisplayed()

Practical Demo– Test ‘Text box’

Test Scenario:  Identify the Gmail Email and Password text box and Enter Value in it           Steps:

  1. Open Gmail Url (gmail.com) in the Browser
  2. Check that Email text box display on the page
  3. Check that Email text box is editable (Enable)
  4. Clear the text box if any text present in the text box
  5. Enter demo@test.com value in the email text box

Script :

System.setProperty(“webdriver.chrome.driver”,”C:\\chromedriver_win32\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
driver.get(“https://accounts.google.com&#8221;); // Step 1 – Open gmail in the chrome Browser
WebElement LoginText = driver.findElement(By.name(“Email”)); // find the webelement of Email text box
boolean chkdisplay = LoginText.isDisplayed(); // Step 2 – Check Email field is display on page or not
if (chkdisplay == true)
{
boolean chkenable = LoginText.isEnabled(); // Step 3 – Check email field is editable or npt
if (chkenable == true)
{
System.out.println(“Email Text box is Present on the page”);
LoginText.sendKeys(“demo@test.com”);
Thread.sleep(2000);
}
else
{
System.out.println(“Email Text box is not editable”);
}
System.out.println(“Text box Test Passed”);
}
else
{
System.out.println(“Email Text box is not present on the page”);
}
driver.close();
}

2. Button

Find “Button” element by locator type ‘id or class or name’

Selenium code

  • findElement(By.id(“submit”))
  • findElement(By.classname(“btn btn-info”))
  • findElement(By.name(“submit”))

Most common operations perform on Text box (Edit Box)

  • Submit – driver.findElement(By.id(“Email”)).submit() // This method works well/better than the click()

3. Link Text

Find “Link Text” element

  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on text present within the <a> </a> tags and identify the web element.

Selenium code

  • findElement(By. linkText(“Link Text name”)
  • Most common operations perform on Link Text
  • Click – findElement(By. linkText(“Link name”)).click()

Demo – Test ‘Button’, ‘Link Text’

Test Scenario:  Click on Submit button

Steps:

  1. Launch new Browser
  2. Open URL http://toolsqa.wpengine.com/automation-practice-form/
  3. Identify Submit button with ‘tagName’, convert it in to string and print it on the console
  4. Click on submit button
  5. Click on the Link “Link Test”

Script:

WebDriver driver = new ChromeDriver();
driver.get(“http://toolsqa.com/automation-practice-form/&#8221;); // Step 1 – Open gmail in the chrome Browser
//Find sumit button and click
String sClass = driver.findElements(By.tagName(“button”)).toString();
System.out.println(sClass);
WebElement button = driver.findElement(By.id(“submit”));
button.submit();

//button.submit(); // Use submit method to click
//Find Link by name and click
Thread.sleep(2000);
WebElement linkText = driver.findElement(By.linkText(“Link Test”));
linkText.click();
System.out.println(“Button and Link Test Passed”);
driver.close();

4. Check Box/Radio button

  • Find “Check Box” element by locator type ‘id or name’
  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on single or group of Radio Buttons/Check Boxes and identify the web element.

Selenium code

  • WebElement radioBtn = driver.findElement(By.id(“toolsqa”));
  • List  oRadioButton = driver.findElements(By.name(“toolsqa”));
  • WebElement oCheck Box=driver.findElement(By.cssSelector(“input[value=’Selenium IDE’]”));

Name is always same for the same group of Radio Buttons/Check Boxes but their Values are different

Most common operations perform on Radio Buttons/Check Boxes

  • Click – driver.findElement(By.id(“toolsqa”)).get(1).click()
  • Is Selected – booleanbValue = findElement(By.id(“toolsqa”)).get(2).isSelected()
  • Fine check box text – StringsValue = findElement(By.id(“toolsqa”)).get(1). getAttribute(“value”)

Demo – Test ‘Radio and check box’

Test Scenario : Select Year of experience radio button one by one

Steps:

  1. Open URL http://toolsqa.wpengine.com/automation-practice-form/
  2. Identify the Gender radio buttons and Select the ‘Female’ radio button by Value
  3. Identify Year of Experience radio buttons by name and select each radio button one by one
  4. Select Year of Experience radio button one by one
  5. Identify the Profession check box and Select the ‘Automation Tester’ check box  by value

Script:

WebDriver driver = new ChromeDriver();
// Step 1: Open Test URL
driver.get(“http://toolsqa.com/automation-practice-form&#8221;);

// Step 2: Identify the Gender radio buttons and Select the ‘Female’ radio button by Value
List<WebElement> rdBtn_Sex = driver.findElements(By.name(“sex”)); //
int size = rdBtn_Sex.size();
System.out.println(“Total no of radio button :”+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute(“value”); // Step 3 – 3. Select the Radio button (female) by Value ‘Female’
System.out.println(“Radio button Name “+sValue);
if (sValue.equalsIgnoreCase(“Female”))
{
rdBtn_Sex.get(i).click();

}
}
// Step 3: Identify Year of Experience radio buttons by name and select each radio button one by one
List<WebElement> rdBtn_exp = driver.findElements(By.name(“exp”));
System.out.println(“Total no of Year radio button :”+rdBtn_exp.size());
for (WebElement wb : rdBtn_exp)
{
wb.click(); // Step 5. Select Year of Experience radio button one by one
Thread.sleep(2000);
}
// alternative for loop
// for(int i =0; i < rdBtn_exp.size() ; i++ )
// {
// rdBtn_exp.get(i).click();
// Thread.sleep(2000);
// }

//Select check box profession ‘Automation Tester’
List<WebElement> chkBox_Prof = driver.findElements(By.name(“profession”));
for (WebElement wbprof : chkBox_Prof)
{
System.out.println(“Profession name “+wbprof.getAttribute(“value”));
if (wbprof.getAttribute(“value”).equalsIgnoreCase(“Automation Tester”)){
System.out.println(“Profession name “+wbprof.getAttribute(“value”));
wbprof.click();
Thread.sleep(2000);
}

}

driver.close();

5. Drop down box

  • Find “Button” element by locator type ‘id, name, Css, Xpath’
  • Step 1: Launch the web browser (Firefox) and navigate to – http://toolsqa.com/automation-practice-form/
  • Step 2: Open firebug
  • Step 3: Click on the inspect icon on drop down box and identify the web element.

Selenium code

  • WebElement element = driver.findElement(By.id(“Country”));
  • Select oSelect = new Select(element);

OR

  • Select oSelect = new Select(driver.findElement(By.id(“Country”)));

Most common operations perform on Radio Buttons/Check Boxes

  • Select by Visible Text – selectByVisibleText(“text”)
  • Select by Index – selectByIndex(4)
  • Select by Value – oSelect.selectByValue(“2016”)
  • Get all option – List<WebElement>elementCount=oSelect.getOptions()
  • Deselect All – deselectAll()
  • Deselect by Index – deselectByIndex(1)
  • Deselect by Value – oSelect.deselectByValue(“string”)
  • Deselect by Text – oSelect.deselectByVisibleText(String arg0)

Demo – Drop down Box/List

  1. Launch new Browser
  2. Open “http://toolsqa.wpengine.com/automation-practice-form/”
  3. Select ‘Continents’ Drop down ( Use Id to identify the element )
  4. Select option ‘Europe’ (Use selectByVisibleText)
  5. Select option ‘Africa’ now (Use selectByIdex)
  6. Print all the options for the selected drop down and select one option of your choice
  7. Close the browser

Script

// Step 1 – Launch Browser
WebDriver driver = new ChromeDriver();
// Step 2 – Open Test URL
driver.get(“http://toolsqa.com/automation-practice-form&#8221;);
// Step 3: Select ‘Continents’ Drop down ( Use Id to identify the element )
Select oSelect = new Select(driver.findElement(By.id(“continents”)));
// Step 4:) Select option ‘Europe’ (Use selectByIndex)
oSelect.selectByVisibleText(“Europe”);
Thread.sleep(2000);

// Step 5: Select option ‘Africa’ now (Use selectByVisibleText)
oSelect.selectByIndex(2);
Thread.sleep(2000);

// Step 6: Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();

// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
}
// Step 7: Kill driver
driver.quit();

6. Web Table

Table is a kind of HTML data which is displayed with the help of <table> tag in conjunction with the <tr> row and <td> column tags.

  • Find “Web Table” by locator type ‘id, name, Xpath’ and find Row and Column by tagName

Demo

  1. Open URL “http://toolsqa.wpengine.com/automation-practice-table/”
  2. Find total no of rows
  3. Find total no of columns
  4. Fetch the Row Header and Column Header and print each cell data

// Step 1: Open Test URL
driver.get(“http://toolsqa.wpengine.com/automation-practice-table&#8221;);

// Step 2: Find total number of rows having effective data
WebElement tbl_rows = driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody”));
List<WebElement> rows = tbl_rows.findElements(By.tagName(“tr”));
System.out.println(“Total No of Rows :”+rows.size());

//Step 3: Find total number of columns
WebElement tbl_cols = driver.findElement(By.xpath(“.//*[@id=’content’]/table/thead/tr”));
List<WebElement> cols = tbl_cols.findElements(By.tagName(“th”));
System.out.println(“Total No of Columns :”+cols.size());
System.out.println(“Total No of Cells :”+ cols.size() * rows.size());

// Step 4: Fetch the Row Header and Column Header and print each cell data
for (int i=1;i<=rows.size();i++){
String tbl_header = driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody/tr[” + i + “]/th”)).getText();
System.out.println(“Item ” +i +” : “+tbl_header);
for (int j=1;j<cols.size()-1;j++){
String tbl_title = driver.findElement(By.xpath(“.//*[@id=’content’]/table/thead/tr/th[” + (j+1) +”]”)).getText();
String sColumnValue= driver.findElement(By.xpath(“.//*[@id=’content’]/table/tbody/tr[” + i + “]/td[“+ j +”]”)).getText();
System.out.println(tbl_title +”:”+ sColumnValue);
}
}

driver.close();

Posted in Selenium, Test Automation | Leave a comment

Selenium Web Driver 2.0 Setup and Create First Project

For Quick View visit my you tube video –Setup and Create First Project

Introduction

  • Selenium 2 (Selenium WebDriver) = Selenium 1.0 + WebDriver
  • I will not go in detail to explain selenium 1.0. It just include selenium IDE + Selenium RC and Selenium Grid
  • Selenium 2 has included selenium 1.0 + WebDriver
  • Selenium WebDriver is designed in a simpler and more concise programming interface along with addressing some limitations in the Selenium-RC API
  • Support various programing language to write Test Script (ex. Java, Paython, C#,Ruby,Php..)
  • Support various browsers to Test (ex. Chrome, FireFox, IE, Safari)
  • Support on various OS (ex. Windows, Linux, Mac)
  • Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded.
  • WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

Setup

Create First Selenium Project

  • Launch the Eclipse IDE
  • Create new project or Open project
  • Configure Build Path (Right click on Project > Build Path > Configure Build Path or Go to Project Properties)
  • Open Libraries tab under Java Build Path
  • Add External Jars ( Selenium xx all Jars)
  • Write Test Script for each Test Step

Test Scenario – Successful Login with valid credential in http://phptravels.net

Test Case – Login with valid username and password

Test Steps :

  1. Open Firefox driver
  2. Open Login page url – http://phptravels.net/login
  3. Enter valid email id – user@phptravels.com
  4. Enter valid password – demouser
  5. Press Login button
  6. Verify that user successfully login into the site and display user name on left top corner – John Smith
  7. Close the browser

Scripts:

package SmokTest;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

public class Login {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

System.setProperty(“webdriver.chrome.driver”, “C:\\chromedriver_win32\\chromedriver.exe”);

WebDriver driver = new ChromeDriver(); // Step 1 – Open Firefox Browser

//WebDriver driver = new FirefoxDriver();

driver.get(“http://phptravels.net/login&#8221;); // Step 2 – Open Web app URL

System.out.println(“Launches Chrome browser successfully”);

driver.findElement(By.name(“username”)).sendKeys(“user@phptravels.com”); //step 3

driver.findElement(By.name(“password”)).sendKeys(“demouser”); //step 4

driver.findElement(By.xpath(“.//*[@id=’loginfrm’]/div/div[5]/div/div/div[1]/button”)).click(); //step 5

Thread.sleep(5000);

String WelcomeMsg = driver.findElement(By.xpath(“.//*[@id=’top’]/div[5]/div[1]/div[1]/h3”)).getText();

System.out.println(“Welcome :”+WelcomeMsg);

Assert.assertEquals(“Hi, John Smith”, WelcomeMsg, “Not matched Login msg”);

driver.close(); // Close the browser

}

}

Posted in Selenium, Set up | Leave a comment

Selenium integration with Cucumber BDD

Cucumber – a Behavior Driven Development (BDD) framework which is used with Selenium for performing acceptance testing.  It allows automation of functional validation in easily readable and understandable format (like plain English) to Business Analysts, Developers, Testers, etc.

Behavior Driven Development is extension of Test Driven Development and it is used to test the system rather than testing the particular piece of code.

I am using eclipse – Eclipse Java EE IDE for Web Developers. Version: Indigo Service Release 2

  1. Create new Java Project. Enter Project Name and click on Next
  2. Click on “Add External Jar” button and add all cucumber jars mention below        Cucumber1
  3. Add Selenium Jar – selenium-server-standalone-2.53.0.jar
  4. Add cucumber plugin in selenium
    1. Help > Install New Software
    2. http://cucumber.github.com/cucumber-eclipse/update-siteCucumber2
  5. Now add new file in project with extension .featureCucumber3
    1. Feature Files: Feature files are essential part of cucumber which gives information about the high level business functionality. Everybody should be able to understand the intent of feature file by reading the first Feature step.
    2. Scenario: Basically a scenario represents a particular functionality which is under test.By seeing the scenario user should be able to understand the intent behind the scenario and what the test is all about. Each scenario should follow given, when and then format. This language is called as “gherkin”.
      1. Given: As mentioned above, given specifies the pre-conditions. It is basically a known state.
      2. When: This is used when some action is to be performed. As in above example we have seen when the user tries to log in using username and password, it becomes an action.
      3. Then: The expected outcome or result should be placed here. For Instance: verify the login is successful, successful page navigation.
      4. Background: Whenever any step is required to perform in each scenario then those steps needs to be placed in Background. For Instance: If user needs to clear database before each scenario then those steps can be put in background.
      5. And: And is used to combine two or more same type of action.Example:Feature: Facebook Login FunctionalityScenario: Test Valid Facebook Login Functionality
        Given user navigates to facebook.com

        When user logs in using Username as “USER”
        And password as “password”
        Then login should be successful
        And Home page should be displayed

    3. Junit Runner:To run the specific feature file cucumber uses standard Junit Runner and specify tags in @Cucumber.import org.junit.runner.RunWith;
      import cucumber.api.CucumberOptions;
      import cucumber.api.junit.Cucumber;

      @RunWith(Cucumber.class)
      @CucumberOptions(
      features = “features”,
      glue = {“stepDefination”},
      plugin={“html:target/cucumber-html-report”}
      )
      public class TestRunner {

      }

    4. Implement feature file:public class smokeTest {WebDriver driver;

      @Given(“^Open firefox and start Gmail$”)
      public void Open_firefox_and_start_application() throws Throwable {

      System.setProperty(“webdriver.chrome.driver”,”C://chromedriver_win32//chromedriver.exe”);
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.get(“http://www.gmail.com&#8221;);
      }

      @When(“^Enter valid Gmail username and password$”)
      public void Enter_valid_username_and_password() throws Throwable {
      // Write code here that turns the phrase above into concrete actions
      driver.findElement(By.name(“Email”)).sendKeys(“LoginUserName”);
      driver.findElement(By.name(“Passwd”)).sendKeys(“LoginPassword”);
      driver.findElement(By.id(“submit”)).click();
      }

      @Then(“^user should be able to login successfully$”)
      public void user_should_be_able_to_login_sccussfully() throws Throwable {
      // Write code here that turns the phrase above into concrete actions
      driver.quit();
      }

  6. Data Driven Testing in cucumber using Scenario Outline: Scenario outlines are usedwhen same test has to be performed with different data set. Let’s take the same example. We have to test login functionality with multiple different set of username and password.

                  Feature: Facebook Login Functionality
                  Scenario: Test Valid Facebook Login Functionality
                  Given user navigates to facebook.com
                  When Enter valid Gmail “<username>” and “<password>”
                   Then login should be successful

Examples:

|username         |password          |

|TestUser1          |password         |

|TestUser2          |password2        |

|TestUser3           |password3        |

Examples are used to pass different arguments in tabular format. Vertical pipes are used to separate two different columns. Examples can contain many different columns.

To implement the Feature file with Examples need to update its implementation with parametrize:

@When(“^Enter valid Gmail \”([^\”]*)\” and \”([^\”]*)\”$”)

public void Enter_valid_username_and_password(String uname,String pwd) throws Throwable {

// Write code here that turns the phrase above into concrete actions

driver.findElement(By.name(“Email”)).sendKeys(uname);

driver.findElement(By.name(“Passwd”)).sendKeys(pwd);

driver.findElement(By.id(“signIn”)).click();
}

 

Posted in Selenium, Set up | Leave a comment