Cucumber – What is Gherkin

HOME

Feature: Book flight ticket for one-way trip
Scenario:flight ticket for one-way trip from Dublin 

Given I live in Dublin 
And I want to book one way flight ticket from Dublin for 22nd Jan 20
When I search Online 
Then TripAdvisor should provide me options of flight for 22nd Jan 20 
And Cost of my flight should not be more than 50 
And Tickets should be refundable

What is Step Definition?

It is a Java method with an expression, which is used to link it to Gherkin steps. When Cucumber executes a Gherkin step, it will look for a matching step definition to execute.

Feature: Book flight ticket for one-way trip
Scenario: flight ticket for one-way trip from Dublin 
Given  I live in Dublin 
 
@Given ("I live in Dublin") 
public voidVacation()
          {
                   System.out.println("I live in Dublin");
          }

When Cucumber encounters a Gherkin step without a matching step definition, it will print a step definition snippet with a matching Cucumber Expression. We can use this as a starting point for a new step definition.

Scenario: Flight ticket for one-way trip from Dublin 
Given  I live in Dublin

Here, Cucumber didn’t get step definition for the above-mentioned Given step. So, it will provide a snippet as mentioned below:-

@Given ("I live in Dublin")
public void i_live_in_Dublin() {
          // Write code here that turns the phrase above into concrete actions
 
    throw new cucumber.api.PendingException();
}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Introduction of Cucumber Testing Tool (BDD Tool)

 
 

In this tutorial, we will discuss about Cucumber Testing Tool. However, before starting with Cucumber, we should know what Behavior Driven Development (BDD) is.

What is Behavioral Driven Development (BDD)?

BDD is a set of practices that helps to reduce the rework caused by misunderstanding or vague requirements, narrow the communication gaps between the development team, testing team, and customers and promote continuous communication among them. In BDD, tests are written in plain descriptive English (Gherkin) and they are more user-focused. As the tests are in plain English, so everyone like Business stakeholders, Business Analyst, QA Team, and Developers can contribute to testing. Cucumber is one such open-source tool, which supports Behavior Driven Development (BDD). In simple words, Cucumber can be defined as a testing framework, driven by plain English. It serves as documentation, automated tests, and development aid – all in one.

How Cucumber works? 

  • Cucumber reads the code written in plain English text (Language Gherkin) in the feature file.
  • It finds the exact match of each step in the step definition.
  • The piece of code to execute can be different software frameworks like Selenium, Ruby on Rails, etc. 
  • This has become the reason for Cucumber’s popularity over other frameworks, like JBehave, JDave, Easyb, etc.

Cucumber supports over a dozen different software platforms like − 

  • Ruby on Rails 
  • Selenium 
  • PicoContainer 
  • Spring Framework 
  • Waitr

Advantages of Cucumber Over other Tools 

  • Cucumber supports different languages like Java.net and Ruby. 
  • It acts as a bridge between the business and technical language. We can accomplish this by creating a test case in plain English text. 
  • It allows the test script to be written without knowledge of any code; it allows the involvement of non-programmers as well. 
  • It serves the purpose of an end-to-end test framework, unlike other tools. 
  • Due to simple test script architecture, Cucumber provides code re-usability.

Example of a Cucumber/BDD test: 

Feature: Book flight ticket for one-way trip
Scenario: Book flight ticket for one-way trip from Dublin to London 

Given I live in Dublin 
And I want to book one way flight ticket from Dublin to London for 23rd Oct 19
When I search Online 
Then TripAdvisor should provide me options of flight for 23rd Oct 19 
And Cost of my flight should not be more than 50 Euro per person 
And Tickets should be refundable

Any Business User or Stakeholder can understand the above-mentioned test case. They can provide their feedback, on if this is expected from the functionality or not or do we need to add other steps too.

How to install Maven on Windows

HOME

Step 2 – Unzip the downloaded folder and then it will have below-mentioned files. We do not need to install anything, just unzip the folder.

Step 3 – We need to configure MAVEN_HOME environment variable. Type – “View Adva” in the search option, and we will see the option – View Advanced system setting.

Step 4 – In the System Properties dialog, select the Advanced tab and click on the Environment Variables button.

Step 5 – In the “Environment variables” dialog, under Users variables, Click on the New button and add a MAVEN_HOME variable.

Step 6 – A dialog box will appear, mentioning Variable Name – MAVEN_HOME and Variable value – mention the path where the Apache folder is placed.

Step 7 – Add %MAVEN_HOME%\bin (full path till bin where Maven is placed on your machine) to Path present under System variables. Click the New Button present in System Variable and add MAVEN_HOME\bin.

Step 8 – Once the Path is updated with %MAVEN_HOME%\bin. This is what it will look like.

Step 9 – We have to make sure that JDK is installed and the JAVA_HOME environment variable is configured. If the JAVA_HOME variable is not configured, then add JAVA_HOME just like MAVEN_HOME in User Variable within Environment Variables.

How to verify if Maven is installed properly on your machine

Open the command prompt and type mvn -version, then the screen should look something like as shown below screen

This confirms that Maven is installed successfully and configured on your machine.  

Constructors in Java

 
 

A constructor initializes an object when it creates. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Every time an object is created using the new() keyword, at least one constructor is called.

ConstructorDemo demo = new ConstructorDemo();

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. Let me explain constructor with the help of a simple program. Here I have created a class ConstructorDemo, created its constructor and then create the object demo which will in turn will call the constructor too.

//Create a Class ConstructorDemo 
public class ConstructorDemo   
{ 
   int x;
 //Create a Constructor for class ConstructorDemo 
   ConstructorDemo()
   {
                   x=24;
   }
         public static void main(String[] args) {
            
                //Create an object of class Constructor and will call the constructor
                 ConstructorDemo demo = new ConstructorDemo();
                  System.out.println("Value of x: "+demo.x);
      }
} 

Output
Value of x:24

Things to remember for a Constructor:-

  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

No Argument Constructor – Here, constructor does not have any argument.

public class DefaultConstructorStudent {
    String Name;
     DefaultConstructorStudent()
    {
            System.out.println("Display details of Student");
       }
      public static voidmain(String[] args) {
           DefaultConstructorStudent stud = newDefaultConstructorStudent();
     }
}

Output
Display details of Student

Parameterized Constructor – A constructor that has a specific number of parameters called a parameterized constructor.

In this example, I have a parameterized constructor with two parameters Name and RollNo. While creating the objects stud1 and stud2, I have passed two arguments so that this constructor gets invoked after creation of stud1 and stud2.

public class ParameterizedStudent {
    String Name;
    int RollNo;
ParameterizedStudent(String New_Name,int New_RollNo)

     {
          Name = New_Name;
          RollNo = New_RollNo;
     }
 
   void DisplayInformation()
   {
        System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo);
   }
        public staticvoid main(String[] args) {
 
            ParameterizedStudent stud1 = newParameterizedStudent("TOM",001);
            ParameterizedStudent stud2 = newParameterizedStudent("MIKE",002);
            stud1.DisplayInformation();
            stud2.DisplayInformation();              
       }
}
 
Output 
Name: TOM, Roll_No: 1
Name: MIKE, Roll_No: 2

Constructor Overloading – This is same as method overloading. Here will have more than one constructor with different parameter lists. Constructors overloaded if they have either different number or parameters, different data type of parameters or different sequence of parameters.

public class ConstructorOverloading {
      String Name;  
      int RollNo;
      int Age;

      //Constructor 1 
      ConstructorOverloading(String New_Name, int New_RollNo, int New_Age)
      {
          Name  = New_Name;
          RollNo = New_RollNo;
          Age = New_Age;
      }

      //Constructor 2
       ConstructorOverloading(int R, int A)
       { 
           RollNo = R;
           Age = A;              
       }

      //Constructor 3 
       ConstructorOverloading(String SName, int SRollNo)
       {
           Name = SName;
           RollNo =SRollNo;
       }
       voidDisplayInformation()
       {
            System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo+","+"Age: "+Age);
       }

      public static void main(String[] args) {
        ConstructorOverloading stud1 = newConstructorOverloading("TOM",001, 20);
        ConstructorOverloading stud2 = newConstructorOverloading(002,21);
        ConstructorOverloading stud3 = newConstructorOverloading("MIKE",003);
        stud1.DisplayInformation();
        stud2.DisplayInformation();
        stud3.DisplayInformation();
     }
}

Output
Name: TOM, Roll_No: 1,Age: 20
Name: null, Roll_No: 2,Age: 21
Name: MIKE, Roll_No: 3,Age: 0

How to automate selecting Checkbox and Radio Buttons in Selenium WebDriver

 
 

In this tutorial, we will see how to identify the form elements like CheckBox and Radio Button

Toggling a CheckBox or Radio Button on/off is also done using the click() method.

IsSelected – IsSelected method, let us know that the element selected or not. Assume there are two Radio Buttons/Check Boxes, one selected by default and you want to select the other one for your test. Then, we use IsSelected method. When there is a group of Radio Buttons/Check Boxes on the page then, most probably, their names are same, but values are different. Then we use the Webdriver findElements command to get the list of web elements.

Below is the working example of CheckBox.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class Checkbox_Test {
     
      public static void main(String[] args) {
            System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver = new ChromeDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
 
           //Single option selection
           System.out.println("*******Single option selection *********");
           driver.findElement(By.id("isAgeSelected")).click();
           String Message = driver.findElement(By.id("txtAge")).getText();
           System.out.println("Message is :"+Message);    
 
       // close the web browser
        driver.close();   
    }
}

Output
*******Single option selection *********
Message is :Success - Check box is checked

How to click all options in the Checkbox

In the below image, there are 4 checkboxes. Initially, when checkboxes were not selected, the test mentioned on the button is – Check All and once all the options are checked, the text on button changes to – Uncheck All.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public classCheckbox_Test {   
     
     public static voidmain(String[] args) throws Exception { 

 System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
          WebDriver driver = newChromeDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
 
          //Display the value of Button before clicking the options of checkbox
          String buttontext_beforeclick = driver.findElement(By.xpath(".//*[@id='check1']")).getAttribute("value");
          System.out.println("Text before click :"+buttontext_beforeclick);

          // Find the CheckBox by its classname
          List list = driver.findElements(By.xpath("//input[@type ='checkbox' and @class='cb1-element']") );            
             
          // Get the number of CheckBoxes available
          int CheckBox_Size = list.size();
          System.out.println("Number of Checkbox options :"+CheckBox_Size);             
            
          // Iterate the loop from first CheckBox to last Checkbox
          for(int i=0;i<CheckBox_Size;i++)
          {     
                list.get(i).click();               
           }
          String buttontext_afterclick = driver.findElement(By.xpath(".//*[@id='check1']")).getAttribute("value");
          System.out.println("Text after click :"+buttontext_afterclick); 
    driver.quit();      
     }
}

Output
Text before click :Check All
Number of Checkbox options :4
Text after click :Uncheck All

Similarly, below I have explained Radio Button.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
 public class Radio_Test {

       public static void main(String[] args) {      
 
     System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");

          FirefoxDriver driver = new FirefoxDriver();
          driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
          driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");

          List<WebElement> Radio_Options = driver.findElements(By.name("optradio"));    
  
          // Create a boolean variable which will hold the value (True/False)
          boolean radio_value = false;

          // This statement will return True, in case of first Radio button is selected
         radio_value = Radio_Options.get(0).isSelected();

         //Identify if Radio Button 1 is selected or not. If Button 1 is already selected, then select Button 2
         if(radio_value==true)
         {
              Radio_Options.get(1).click();
              System.out.println("Button Selected is :"+ Radio_Options.get(1).getAttribute("value"));  
         }
         else
         {
               Radio_Options.get(0).click();
               System.out.println("Button Selected is :"+ Radio_Options.get(0).getAttribute("value"));  
          }

          driver.findElement(By.id("buttoncheck")).click();
          String Button_Selected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]")).getText();
          System.out.println("Get Checked Value is :"+ Button_Selected); 
       
         //Group Radio Button Selection
         driver.findElement(By.xpath(".//input[@name='gender'and @value='Female']")).click();
         driver.findElement(By.xpath(".//input[@name='ageGroup' and @value='15 - 50']")).click();
         driver.findElement(By.xpath(".//*[@id='easycont']/div/div[2]/div[2]/div[2]/button")).click();
          String Group_Radio_Message = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[2]/div[2]/p[2]")).getText();

          System.out.println("Get Values are :"+Group_Radio_Message);

         // close the web browser
        driver.close();
      }
}
 
Output
Button Selected is :Male
Get Checked Value is :Radio button 'Male' is checked
Get Values are :Sex : Female
Age group: 15 - 50

Selenium Form WebElement Commands – Sendkeys, Clear, Click, Submit

HOME

WebElement represents HTML DOM(Document Object Model) element. Anything present on web page like alert box, text box, button- all are WebElements.  When HTML loads into a web browser, it is convert into document object

WebElement in Selenium is a generic class that converts object into document object. There are a number of WebElement commands present in Selenium, but in this blog will discuss about

1) sendKeys()
2) clear()
3) Submit()
4) click()

1) SendKeys – This simulate typing into an element, which may set its value. This method accepts CharSequence as a parameter and returns nothing.

This method works fine with text entry elements like INPUT and TEXTAREA elements.

Input boxes refer to either of these two types: 
1. Text Fields– text boxes that accept typed values and show them as they are.
2. Password Fields– text boxes that accept typed values but mask them as a series of special characters (commonly dots and asterisks) to avoid sensitive values to be displayed.

To enter text into the Text Fields and Password Fields, sendKeys() is the method available on the WebElement. 

Syntax:

sendKeys(CharSequence… keysToSend ) : void

Command:

driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

2) Clear – If this element is a text entry element, this will clear the value. This command does not require any parameter and return nothing.

Syntax:

clear( ) : void 

Command:

email.clear(); 

3) Submit – This method works well/better than the click(), if the current element is a form, or an element within a form. This command does not require any parameter and return nothing.

Syntax:

submit():void

Command:

driver.findElement(By.id("u_0_2")).submit(); 

4) Click – This simulates the clicking of any element. This command does not require any parameter and return nothing. 

The buttons can be accessed using the click() method.

Syntax:

click():void 

Command:

driver.findElement(By.id("u_0_2")).click(); 

Let us write a small program to see the use of these commands. I have used both click() and submit commands() to show how they work, but when you try to run this program, comment any one of the part.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class Facebook_Login {
       public static void main(String[] args) {
              System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
             
           // Create a new instance of the Firefox driver
           WebDriver driver = new FirefoxDriver();
 
           driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
           driver.get("https://www.facebook.com/");
           driver.manage().window().maximize();
           WebElement email = driver.findElement(By.xpath("//*[@name = 'email']"));
           WebElement password = driver.findElement(By.xpath("//*[@name = 'pass']"));
           Thread.sleep(1000);
 
          // switch from main window to child window
           for (String handle1 : driver.getWindowHandles()) {
                    driver.switchTo().window(handle1);
           }
 
           driver.findElement(By.id("u_0_k")).click();
 
           // Enter data in Text box
           email.sendKeys("abc123@gmail.com");
           password.sendKeys("Abc123@");
           System.out.println("Data is entered in Text Field");
 
           // Delete values from text box
           email.clear();
           password.clear();
           System.out.println("Data is cleared from Text Field");
 
           // Using submit method to submit the form
           email.sendKeys("abc123@gmail.com");
           password.sendKeys("Abc123@");
           driver.findElement(By.id("u_0_2")).submit();
           System.out.println("Login Done with Submit");
      }
}
      
Output:
Data is entered in Text Field
Data is cleared from Text Field
Login Done with Submit  

Difference between FindElement and FindElements in Selenium WebDriver

 

Identifying the web elements in a page is required to interact with the web page. Selenium WebDriver give us FindElement and FindElements methods to locate elements on the webpage. There are multiple ways to identify uniquely a web element within the web page such as ID, Name, Class Name, LinkText, PartialLinkText, TagName, and XPath.

FindElement Command

This method locates the first web element on the current web page matching the criteria mentioned as parameters.  

If the web element is not found, it will throw an exception – NoSuchElementException.

Syntax:

findElement(By arg0):WebElement - WebDriver

Command:

driver.findElement(By.xpath("Xpath location"));

How to use FindElement in Selenium

The following application is used for demo purposes:

https://www.facebook.com/

Scenario – Valid

  •      Open the web page
  •      Close the child window and move to facebook main page
  •      Enter the emailId and password and click on Log In Button
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver;
public class FindElement_Example { 
        
         public static voidmain(String[] args){
           System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");

         // Create a new instance of the Firefox driver
          WebDriver driver = new FirefoxDriver();
          
        // Set implicit wait of 60 sec for managing waits in selenium webdriver
         driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
                       
        // Launch a new web page and load Facebook
         driver.get("https://www.facebook.com/");
         Thread.sleep(1000); 
            
        //switch from main window to child window
        for (String handle1 : driver.getWindowHandles()) {
               driver.switchTo().window(handle1);
         }
         driver.findElement(By.id("u_0_k")).click();

         // Enter the values in Email and Password Textboxes
         driver.findElement(By.name("email")).sendKeys("abc@gmail.com");
         driver.findElement(By.id("pass")).sendKeys("abcd1234!"); 
               
         // Click on Log In Button
         driver.findElement(By.id("u_0_b")).click();
         driver.close();
    }
}

Scenario – Error

  •      Open the web page
  •      Close the child window and move to facebook main page
  •      Use incorrect locator to find emailId
  •      Execution halts and then stopped with NoSuchElementException
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElement_Example {
        
         public static void main(String[] args){
           System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
    
         // Create a new instance of the Firefox driver
          WebDriver driver = new FirefoxDriver();
                        
         // Set implicit wait of 60 sec for managing waits in selenium webdriver
         driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

         // Launch a new web page and load Facebook
         driver.get("https://www.facebook.com/");
         Thread.sleep(1000);    
         
         //switch from main window to child window
         for (String handle1 : driver.getWindowHandles()) {
                 driver.switchTo().window(handle1);
          }
          driver.findElement(By.id("u_0_k")).click();

         // Enter the values in Email and Password Textboxes
          driver.findElement(By.name("email")).sendKeys("abc@gmail.com");
          driver.findElement(By.id("pass")).sendKeys("abcd1234!"); 
               
          // Click on Log In Button
          driver.findElement(By.id("u_0_b")).click();
          driver.close();
      }
}

FindElements Command

  • This method locates all the web elements on the current web page matching the criteria mentioned as parameter.  
  • If not found any WebElement on current page as per given element locator mechanism, it will return empty list.                                                                                    

Syntax

findElements (By arg0):List

Below is the example of findElements

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElements_Example {
       public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
            // Create a new instance of the Firefox driver
             WebDriver driver = new FirefoxDriver();

             // Set implicit wait of 60 sec for managing waits in selenium webdriver
             driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

             // Launch a new web page and load Facebook
             driver.get("https://www.facebook.com/");
             Thread.sleep(1000);

             // switch from main window to child window
             for (String handle1 : driver.getWindowHandles()) {
                    driver.switchTo().window(handle1);
             }
             driver.findElement(By.id("u_0_k")).click();
             driver.findElement(By.xpath("//*[@id='u_0_2']")).click();

             // Find all elements and store into list
              List Link_List = driver.findElements(By.id("month"));
              for (WebElement link : Link_List)

              // Print all the elements from the list
              System.out.println(link.getText());
               driver.close();
        }
}

Output
Month
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

Differences between findElement() and findElements() method:

·         Return type of findElement() is a WebElement (single) while Return type of findElements() is a List (multiple).

·         findElement() method will throw noSuchElementException if web element is not found in WebPage while findElements() will return an empty list and do not throw any.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

WebDriver Browser Commands – get, getTitle, getCurrentUrl, getPageSource, getClass, close, quit in Selenium WebDriver

WebDriver is a tool for automating web application testing, and in particular, to verify that they work as expected. WebDriver is design to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API. Selenium-WebDriver was develop to better support dynamic web pages where elements of a page may change without the page itself being reload. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems. 

In this tutorial, we are discussing about below mentioned topics:-
1) How to access the methods of WebDriver?
2) Various Browser Commands

  • get()
  • getTitle()
  • getCurrentUrl()
  • getPageSource()
  • getClass()
  • close()
  • quit()

How to access the methods of WebDriver?

To access a method of WebDriver, you need to create a driver object from WebDriver and press. dot key. This will list all the methods. Here, you can see that I have used driver.get, so it will show all the methods starts with get.

Method Name – I have explained earlier about Method. A method is a block of code that is use to perform certain actions. Method runs when it is call. Method name is the name of method we are going to use. 

Parameter Data Type – It is pass as an argument to the method to perform certain operation. Here, string data type is use as an argument. 

Return Type – Methods can return values like getTitle() : String as string is here the return type. In the above example, return type is void means do not return anything.

Browser Commands

1) Get – This command loads a new web page in the current browser window and open the webpage mentioned as argument. It accepts string as parameter and void means returns nothing. 

Syntax

get(String arg0) : void    

Command

Command - driver.get(URL) 

2) Get Title – This command retrieves the title of current web page. It does not accept any parameter and returns a string value. 

Syntax

getTitle() : String   

Command

driver.getTitle()

3) Get Current URL – This command retrieves the URL of current web page. It does not accept any parameter and returns a string value.

Syntax

getCurrentUrl() : String  

Command

driver.getCurrentUrl(); 

4) Get Page Source – This command returns the page source of current web page. . It does not accept any parameter and returns a string value.

Syntax

getPageSource() : String  

Command

driver.getPageSource();

5) Get Class – The command is use to retrieve the Class object that represents the runtime class of this object.

Syntax

getClass() 

Command

driver.getClass(); 

6) Close – This command is use to close the current web browser, which is controlled by WebDriver. This command does not require any parameter and void means return nothing.

Syntax

close(): void 

Command

driver.close()

7) Quit – This command close all the browsers opened by webDriver. This command does not require any parameter and void means return nothing.

Syntax

quit(): void 

Command

driver.quit(); 

Now, let us write a small program to show the use of methods of WebDriver.  

  1. Launch a new Firefox browser
  2. Open facebook.com
  3. Get Page Title name and print
  4. Get Page URL and print on Eclipse Console
  5. Get Page Source (HTML Source code) and Page Source length and print Page length
  6. Get Runtime class name of the object
  7. Close the Browser
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium_Browser_Commands {
    public static void main(String[] args) throws {
         System.setProperty("webdriver.gecko.driver",
                                              "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\geckodriver-v0.27.0-win64\\geckodriver.exe");
 
             // Create a new instance of the Firefox driver 
             WebDriver driver = new FirefoxDriver();
             driver.manage().window().maximize();
 
            // Set implicit wait of 60 seconds
             driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
 
            // Launch a new web page and load Facebook using Get Command
             driver.get("https://www.facebook.com/");
 
             // Get the Title of web page
             String PageTitle = driver.getTitle();
             System.out.println("Title of page is :"+ PageTitle);
 
             // Get URL of current web page
             String PageURL = driver.getCurrentUrl();
             System.out.println("URL of current page is :" + PageURL);
 
             // Get Source code of current web page
             String PageSource = driver.getPageSource();
             int PageSource_Length = PageSource.length();
             System.out.println("Length of page source of current page is :" + PageSource_Length);
 
              // Get Runtime class of this object
              Class<? extends WebDriver> className = driver.getClass();
              System.out.println("className :" + className);
 
              // Close the current web page
              driver.close();
        } 
}

Output
Title of page is :Facebook – log in or sign up
URL of current page is :https://www.facebook.com/
Length of page source of current page is :293624
className :class org.openqa.selenium.firefox.FirefoxDriver

Dynamic XPath in Selenium WebDriver

HOME

//: select the current node.
tagname: name of the tag of a particular node.
@: to select attribute.
Attribute: name of the attribute of the node.
Value: value of the attribute

1) Basic XPath

XPath’s expression selects nodes based on ID, class, etc. from an XML web page.

Go to http://www.facebook.com and inspect the Email or Phone textbox. How to inspect a web element on the web page is explained in the previous blog. Some of the basic examples of XPath is displayed below:

By.xpath("//input[@name='email']")
By.xpath("//input[@id=’email’]")
By.xpath("//input[@type='email']")
By.xpath("//input[@class=’inputtext’]")
By.xpath("//*[@class=’inputtext’]")
By.xpath("//input[@class=’inputtext’][@type='email']")

In the last example, we have created XPath using multiple attributes for the single HTML tag.

Syntax

By.xpath("//a[@href='https://www.facebook.com/']")

2) Contains

It is used if the value of any web element changes dynamically. Using this expression, you can find the element with partial text.

Syntax

By.xpath("//*[contains(@name,'passwd_')]")

3) OR & AND

OR & AND expression uses 2 conditions to identify a web element.

In the case of OR, if any of the conditions is true, then the element will be located. Whereas in the case of AND, both the conditions should be true to locate the element.

Syntax

By.xpath("//*[@class='inputtext' or @name='email']")

Here, if you observe, class – ‘inputtext’ is same for 2 web elements, so with OR condition it will locate 2 web elements.

Syntax

By.xpath("//*[@class='inputtext' and @name='email']")

4) Start-with function 

This function finds the web elements whose value changes dynamically. In the expression, we will use that value of the web element which doesn’t change. Let’s see a small example of using the start-with() function.

Syntax

By.xpath("//*[starts-with(@id,'yui_3_18_0_3_1555510217471_')]")

5) Text() 

This expression is used with the text function to locate an element with exact text. Let me show you how to use the Text() method. 

Syntax

By.xpath("//*[text(),"Create an account"]")

6) Last()

Select the last element (of the mentioned type) out of all input elements present.

Syntax

By.xpath("//input[@type='text'])[last()]")

There are 5 web elements with input type -text. But with this expression, it has selected the last one.

7) Position()

Selects the element out of all input elements present depending on the position number provided

Syntax

By.xpath("//input[@type='text'])[2]")

8) Following

By using this, we could select everything on the web page after the closing tag of the current node.

The xpath of firstname is as follows:-

By.xpath("//*[@name='firstname']")

To identify the input field of type text after the FirstName field, we need to use the below XPath.

By.xpath("//*[@name='firstname']//following::input[@type='text']")

To identify just the input field after the FirstName field, we need to use the below XPath.

By.xpath("//*[@name=’firstname’]//following::input[1]")

9) Preceding

Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes, and namespace nodes.

The XPath of the LastName field is as follows

By.xpath("//*[@name='lastname']")

To identify the web element before lastname field is as follows

By.xpath("//*[@name='lastname']//preceding::input[1]")

To identify the input field of type text before the LastName field, we need to use below XPath

By.xpath("[@name='lastname']//preceding::input[@type='text']")

Now, let’s write a small program to show the use of XPath. In this program, 

  • Firefox is used as the browser. 
  • The path of the Mozilla Firefox driver is set by using System.SetProperty. Mozilla Firefox driver is called gecko, so do not get confused. 
  • driver.get is used to navigate to amazon site. The search box of the webpage is located using XPath – (“//*[@id=’twotabsearchtextbox’]”))
  • sendkeys() is used to search for value hard drive. 
  • Search Button is clicked by using XPath – (“//*[@class=’nav-input’]”))
import java.util.concurrent.TimeUnit; 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class Selenium_Site { 
      public static void main(String[] args) {
              System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            driver.get("https://www.amazon.com//");
            driver.manage().window().maximize();

            //XPath for Search box
            driver.findElement(By.xpath("//*[@id='twotabsearchtextbox']")).sendKeys("hard drive");

            //XPath for search button
            driver.findElement(By.xpath("//*[@class='nav-input']")).click();
     }
}

Methods in Java

HOME

modifier returnType nameOfMethod (Parameter List) {
   // method body  }

Here,

  • modifier − It defines the access type of the method like public, protected, default, private
  • returnType − Method may return a value or not. Void does not return any value.
  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
  • Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
  • method body − The method body defines what the method does with the statements.
public static int methodName(int a, int b) {
      // body
   }

public class Method_Example {

    public static void main(String[] args) {

        //Standard Library Method
        System.out.println("Square root of 9 is : " + Math.sqrt(9));

        //User defined Method
        MyMethod();
    }

    public static void MyMethod()
    {
        System.out.println("My User defined Method");
    }
}

Java Methods with Arguments and Return Value

A Java method can have zero or more parameters, and they may return a value.

public class Min_Method {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        int c = minMethod(a,b);
                System.out.println("Minimum value is :" + c);
    }

    //Define function min_function
    public static int minMethod(int x, int y)
    {
        int min;
        if (x>y)
            min =y;
        else
            min = x;
        //return value
        return min;
    }
}

Void Keyword

The void keyword allows us to create methods that do not return a value. When a method’s return type is void, it means that the method performs some operation or task but does not produce any result that needs to be returned to the caller.

public class Min_Method {

    public static void main(String[] args) {

        int a = 10;
        int b = 5;

        //Call function
        minMethod(a,b);
    }

    //Define function min_function
    public static void minMethod(int x, int y)
    {
        int min;
        if(x>y)
            min =y;
        else
            min = x;
        System.out.println("Minimum value is :" + min);
    }
}

Method Overloading

When a class has two or more methods by the same name but different parameters, it known as method overloading. To know more about method overloading, click here.

public class Overloading_Example {
    
        public static void main(String[] args) {

            int a= 10;
            int b = 24;
            double c = 12.0;
            double d = 13.0;
            min_function(a, b);
            min_function(c,d);
        }

        public static void min_function(int x, int y)
        {
            int min;
            if(x>y)
                min = y;
            else
                min = x;

            System.out.println("Minimum value for integer is :"+ min);
        }

        public static void min_function(double m, double n)
        {
            double min;
            if(m>n)
                min=n;
            else
                min=m;
            System.out.println("Minimum value for integer is :"+ min);
        }
    }

What is main method in Java?

The main()method is the entry point into the application. The signature of the method is always: public static void main(String[] args).