Web Services

What is Web Service Testing?

Web Services Testing is testing of Web services and its Protocols like SOAP & REST. To test a Webservice you can

  1. Test Manually
  2. Create your own Automation Code
  3. Use an off-the shelf automation tool like SoapUI.
  • Web service is is technology which allow communicate between different languages. It allow us to pass the data over the internet in easy way.
  • In other word Web services provides an easy way to achieve interoperbility.
  • It follow collection of standareds or protocols for exchanging information between two device over internet/network.
  • Ex – Java can easilty interact with Ruby, Paython etc using Web Services.
  • Request – A request which is initated by Client.
  • Response – A respose send by server based on client request

SOAP (Simple Object Access Protocol)

  • SOAP can interact with other programing language applications.
  • It is just a protocol which is XML Based for accesing web service over the interne

Adv

  • it has own security known as WS Security.
  • Language and Platform indenpendent.

Disadv

  • It support only XML format
  • It works with WSDL file only so we can’t have other format like JSON, Header etc..

Restful Web Services

  • Rest stands for Representational State Transfer
  • Platform dependent
  • support multiple format like JSon, Html, XML, Plain text file too.
  • Fast compared to SAP
  • its not a protocol liks SOAP it just a architectural design.
  • Restfull is most widly used now a days

Response Codes

  • 1xx information based
  • 2xx (ex. 200) Success
  • 3xx Redirection
  • 4xx Client Error
  • 5xx Server Error

WebService Testing involves following steps –

  1. Understand the WSDL file
  2. Determine the operations that particular web service provides
  3. Determine the XML request format which we need to send
  4. Determine the response XML format
  5. Using a tool or writing code to send request and validate the response

WSDL

WSDL (Web Services Description Language) is an XML based language which will be used to describe the services offered by a web service.

WSDL describes all the operations offered by the particular web service in the XML format. It also defines how the services can be called, i.e what input value we have to provide and what will be the format of the response it is going to generate for each kind of service.

Using SoapUI to Test the WebService

In SoapUI

  1. Go to File > New Soap Project
  2. Enter the project Name and the WSDL URI location
  3. Click OK

SoapUI_NewProject

  1. Expand the first request and double click on the ‘Request1’. It will display the SOAP request in the XML format.
  2. Enter the From Currency and To Currency
  3. Click on the submit button
  4. Response XML will be displayed right side pane.

SoapUI_Request_Respose.png

Advertisements
Posted in Web Service | Leave a comment

Java Oops Concepts

 

Inheritance : use parent class veriable and method using child class object

  1. Create object of child class and reference of child class, using this object access all methods of base class and child class

2. Create object of base class and reference of base class, allow to access all method of base class only

3. Create reference of base class but object of child class, allow to access method of base class only not child class method

Inheritance – http://www.software-testing-tutorials-automation.com/2014/04/inheritance-in-java-tutorials-for.html

Interface implement in selenium – http://www.ufthelp.com/2015/01/Java-Interface-example-in-Selenium.html

Polymorphism

2 Type of Polymorphism

  1. Compile time called early binding

Overloading : Same method name but different signature(No of arguments, Type of arg,order of arg)

e.x. add(int a, int b) and add(int a, int b, int c)

2. Runtime called Late biding

OverRidding

Abstraction

Showing the functionality by hiding the implemetation details.

Abstact class must have atleast one abstract method

Abstract class have both concreate and abstract method

In Abstract class you can define member variables

common functionality define in the abstract class and functionalty change in subclass define in asbstract method

when extend abstract class then going to implement in sub class to achive the code resuability

example:

abstract class Bank 
{
   public void diposite() {
         system.out.println("common deposite method across all banks");
    }
    public void withdraw() {
        system.out.println("common withdraw method across all bank");
     }

public abstract int calculteInterest();
}

every bank have different formula to calculating the interest so extands bank class will implement the calculateInterest method()

class HDFC extends Bank{
  @override
  public int calcualteInterst(){
      System.out.println("HDFC bank Calculate Interest Implentation");
  }
}
Bank hdfc = new HDFC();
hdfc.diposite();
hdfc.withdraw();
hdfc.calcualteInterst();

Interface

In Interface all methods are bydefault abstract

public interface BankInterface {
   public abstract  void diposite();
   public abstract void withdraw();
   public abstract void calculateInterest();
}

bydefault declare method is public even define or not.

Class impements the interface must have to define the method

class HDFC implements BankInterface{
 @override
  public void depostie(){
     System.out.println("HDFCBank deposite Implementation");
  }
  @override
  public void withdraw() {
      System.out.println("HDFCBank withdraw implentation");
  }
  @override
  public void calculateInterest(){
      System.out.println("HDFCBank calculate interest implementation");
  }
}
Bankinterface hdfcbank = new HDFCBank();
hdfcbank.deposite();
hdfcbank.withdraw();
hdfcbank.calculateInterest();

By using the interface achive multiple inheritance

Posted in Uncategorized | Leave a comment

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.

Maven & Jenkins with Selenium

https://www.guru99.com/maven-jenkins-with-selenium-complete-tutorial.html#2

Selenium-Git Configuration

http://www.guru99.com/selenium-github.html

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();

XPath 

Difference between single ‘/’ or double ‘//’

Single slash ‘/’ anywhere in xpath signifies to look for the element immediately inside the parent element.

Double slash ‘//’ signifies to look for any child or nested-child element inside the parent element.

Syntax:

//tag[@attribute=’value’]

Relative xpath using single ‘/’ for Login link

//div[@id=’navbar’]/div/div/div/ul/li[2]/a

Relative xpath using double ‘//’ for Login link.

//div[@id=’navbar’]//ul/li[2]/a

Don’t use “*”, always use the tag name.

Using Text of the element to build xpath

Finding Login link:

//div[@class=’homepage-hero’]//a[text()=’Enroll now’]

Using Contains to find the elements:

Syntax: //tag[contains(attribute, ‘value’)]

Finding Login link:

//div[@id=’navbar’]//a[contains(text(),’Login’)]

//div[@id=’navbar’]//a[contains(@class,’navbar-link’) and contains(@href,’sign_in’)]

Using Starts-With to find the elements:

Syntax: //tag[starts-with(attribute, ‘value’)]

Finding Login link:

//div[@id=’navbar’]//a[starts-with(@class,’navbar-link’)]

Parent

Syntax: xpath-to-some-element//parent::<tag>

 Preceding Sibling

Syntax: xpath-to-some-element//preceding-sibling::<tag>

Following Sibling

Syntax: xpath-to-some-element//following-sibling::<tag>

Exercise:

Find the price of the course “Python Programming Language”

Solution:

//table[@id=’product’]//td[text()=’Python Programming Language’]//following-sibling::td

Find Author of the book “The Green Mile”

Solution:

//div[@id=’gridbox’]//a[text()=’The Green Mile’]//parent::td//following-sibling::td[1]

Posted in Selenium, Test Automation | Leave a comment