Grab Deal : Flat 30% off on live classes + 2 free self-paced courses! - SCHEDULE CALL

- Selenium Blogs -

Simple and Important Guidance For You In Selenium Test Case



Introduction

You have gone through Selenium Basics. By using all those concepts you can write a Selenium Test Cases. In this article, you will learn How to write Different types of Selenium Test Cases. You already know how to set up the environment. Once Environment is set up, you are also ready to start writing cases.

Test Case 1 : How to verify Internal and External Links of any WebPage.

Scenario: On any webpage, you have seen a number of Links that can be seen in the form of Hyperlink. Now you want to access all the links and want to segregate them. They might be internal and External links. Some might be broken links also. Internal Links are those links that exist on your webpage and refer to your domain.

Learn QA Software Testing in the Easiest Way

  • Learn from the videos
  • Learn anytime anywhere
  • Pocket-friendly mode of learning
  • Complimentary eBook available

 External Links are those links that refer to a different domain. In the below example you will get to know how to calculate all the links that exist on the page and Number of External and Internal Links.

Step1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “VerifyExternalAndInternalLink”.

Step 3: Set the Browser Property on which browser you want to run the script.

//Create a variable of WebDriver
  WebDriver driver;
  // To run the script set the path for chrome driver 

   System.setProperty("webdriver.chrome.driver", ".\\driver\\chromedriver.exe");

 // Initialize the driver instance with Chrome Browser    driver=new ChromeDriver(); 

Step 4: Launch the browser and Maximize the window and Apply the implicit wait //Open the Browser
driver.get("https://www.flipkart.com");       // Maximize the Window   driver.manage().window().maximize();   // Apply implicit wait   driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

Step 5:Store all the LInks in a list and access them.

List links=driver.findElements(By.tagName("a"));

Step 6 : Calculate total number of links and Segregate Total Number of External link and Internal link.  

System.out.println(" Total number of links exist on page"+links.size());

  int internal_link_count=0;

      int external_link_count=0;
try {
     for(int i=0;i

external_link_count++;
}

}
}catch(NullPointerException e) {
 e.getMessage();

}
System.out.println("Total External links are"+external_link_count);
;System.out.println("Total internal links are"+internal_link_count);

driver.quit();

}
Step 7: Now run the code by right click and Run the java Application. I have already described that one.
Selenium Test Script in Eclipse:

Output of the script :

Explanation of code: Here the Total number of links you can see 829+11=840. And External links are like https://www.facebook.com/flipkart  and Internal links are like https://www.flipkart.com/pages/payments means which start with Flipkart itself.

QA Software Testing Training

  • No cost for a Demo Class
  • Industry Expert as your Trainer
  • Available as per your schedule
  • Customer Support Available

Test Case 2: Test Case: Verify Element Existence.

Scenario: To verify Element Existence is a very Selenium Test SCript is a very interesting and widely used topic. It is mostly used in each Selenium Test Script when you will start to work with any Framework. When you apply Explicit wait then You verify Element Existence to halt the driver till the element visible or clickable. There are a number of different ways by using you can check the Element existence on the page. You will learn from this example.

Step 1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “VerifyElementExistance”.

Step 3: Set the Browser Property on which browser you want to run the script

//Create a variable of WebDriver

WebDriver driver;
// To run the script set the path for chrome driver 

System.setProperty("webdriver.chrome.driver", ".\\driver\\chromedriver.exe");
// Initialize the driver instance with Chrome Browser

driver=new ChromeDriver();  

Step 4: Launch the browser and Maximize the window and Apply the implicit wait


//Open the Browser

driver.get("https://www.flipkart.com");

// Maximize the Window

driver.manage().window().maximize();
;// Apply implicit wait
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

Step 5: Verify Highlighted Cross Icon on Login Modal is visible or not.


WebElement loginmodal_close_button=driver.findElement(By.xpath("//div[@class='_3Njdz7']/button"));

//loginmodal_close_button.click();

//By Verify Element Visibility

boolean existence=loginmodal_close_button.isDisplayed();

try {

if(existence)

System.out.println("Element present on page");

else 

System.out.println("Element not present on page");

}catch(StaleElementReferenceException e) {

e.getMessage();

}

 Here WebElement.IsDisplayed Method we are using. You can use WebElement.isSelected, WebElement.isEnabled method also. It depends on the Scenario you can use in your Test Script.

 

Step 6: Verify Login modal is open or not by verifying Text on Modal.

// By verify Element Text

 WebElement login_modal_text=driver.findElement(By.xpath("//div[@class='Og_iib col col-2-5 _3SWFXF']/span/span")); 

 String text=login_modal_text.getText(); 

 System.out.println("Text of Element"+text); 

 if(text.contentEquals("Login")) { 

 System.out.println("Element correctly identified"); 

 } 

Here in the WebElement store the Text which is actually coming on Login Modal using the script After that Verify both Actual and Expected Data.

Complete code in Eclipse : 

OutPut of the Script :

Test Case 3 :Login to gmail

Scenario: This is a very SImple Test case that is required for each application. To enter login id and password to login to account. So Let's have a look at How you can log in to the Gmail account using the Selenium test script.

Note:  If you run your Gmail account login script in Chrome Browser you might face below error

QA Software Testing Training

  • Personalized Free Consultation
  • Access to Our Learning Management System
  • Access to Our Course Curriculum
  • Be a Part of Our Free Demo Class

That's why I have created the script using the IE browser. Also in the IE browser, there is a problem you might face. Unable to click. So I have added DesiredCapability to make click accessible. I will explain in the next blog What is Desired Capability. 

Step1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “LoginToGamilAccount”.

Step 3: Set the Browser Property on which browser you want to run the script.

//Create a variable of WebDriver 
 WebDriver driver; 

 // To run the script on IE browser set the path  
 System.setProperty("webdriver.ie.driver", ".\\driver\\IEDriverServer.exe"); 
 // Initialize the driver instance with IE Browser 

 >DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer(); 

 ieCapabilities.setCapability("nativeEvents", false); 

 ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept"); 

 ieCapabilities.setCapability("ignoreProtectedModeSettings", true); 
ieCapabilities.setCapability("disable-popup-blocking", tru

Step 4:  Launch the browser and Maximize the window and Apply the implicit wait

//Open the Browser 
 driver.get("https://accounts.google.com/signin"); 
  
  // Maximize the Window 
 driver.manage().window().maximize(); 
 // Apply implicit wait 

 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); 

Step 5 : Locate the email id and password fields and Eneter the credentials

driver.findElement(By.xpath("//input[@type='email']")).sendKeys("Gmail Account Id");

 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 
 
 driver.findElement(By.xpath("//input[@name='password']")).sendKeys("Gmail account password"); 
 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 

Step 6: Close the driver.

driver.close(); 
 Complete code in Eclipse : 

Test Case 4: Verify Customer Registration in on a new email.

Scenario: How to fill the Gmail new account form you will learn with this example. After filling the Registration form, Google accounts to verify your phone number which will you learn later. So at this stage, you first should know How you can enter the correct information in google account creation form.

QA Software Testing Training

  • Detailed Coverage
  • Best-in-class Content
  • Prepared by Industry leaders
  • Latest Technology Covered

Let's have a look at the below code to achieve this.

Step1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “GmailRegistration”.

Step 3: Set the Browser Property on which browser you want to run the script.

//Create a variable of WebDriver 
 WebDriver driver; 
// To run the script set the path for chrome driver  
 System.setProperty("webdriver.chrome.driver", ".\\driver\\chromedriver.exe"); 
 // Initialize the driver instance with Chrome Browser 
 driver=new ChromeDriver(); 

Step 4: Launch the browser and Maximize the window and Apply the implicit wait.

//Open the Browser 
 driver.get("https://accounts.google.com/signin"); 
 // Maximize the Window 
 driver.manage().window().maximize(); 
 // Apply implicit wait 
 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); 

Step 5 . Click on Create account link and For Myself drop down value

driver.findElement(By.xpath("//span[contains(text(),'Create account')]")).click(); 

 driver.findElement(By.xpath("//div[contains(text(),'For myself')]")).click(); 

Step 6: Now fill all the details. Your First name, Last name, new email id, Password and confirm password.

driver.findElement(By.xpath("//input[@type='text' and @aria-label='First name']")).sendKeys("Name"); 
 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Last name']")).sendKeys("Name"); 

 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Username']")).sendKeys(""); 

 driver.findElement(By.xpath("//input[@type='password' and @aria-label='Password']")).sendKeys("password@1"); 
 driver.findElement(By.xpath("//input[@type='password' and @aria-label='Confirm']")).sendKeys("password@1"); 

 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 

Step 7. Verify user is able to access Verify Phone number screen or not

String next_screen=driver.findElement(By.xpath("//div[@jsname='paFcre']/div/h1[@class='sfYUmb']")).getText(); 

 System.out.println(next_screen); 

 if(next_screen.contains("Verifying your phone number")) { 

  System.out.println("Registration successfully using gmail entered"); 
 
 } 

 else { 

 System.out.println("Please eneter correct email id or password"); 

 } 

Step 8 : Close browser

 driver.close(); 
Complete code in Eclipse

:

Explanation of Code: Hereafter filling the complete registration form if the driver reached to next screen then you will get the message “ Registration successfully using Gmail entered” else “Please enter correct email and password”..

Output of the script :

Test Case 5: Check Error Message/s in Login Functionality (Negative Test Case)

Scenario: It is very important to verify login functionality with invalid Credentials. In this Selenium Test Script you will learn how to achieve this :

Step1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “VerifywithWrongLoginName”.

Step 3: Set the Browser Property on which browser you want to run the script.

//Create a variable of WebDriver 

 WebDriver driver; 

 // To run the script on IE browser set the path  

 System.setProperty("webdriver.ie.driver", ".\\driver\\IEDriverServer.exe"); 

 // Initialize the driver instance with IE Browser 

 DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer(); 

 ieCapabilities.setCapability("nativeEvents", false); 

 ieCapabilities.setCapability("unexpectedAlertBehaviour", "accept"); 

 ieCapabilities.setCapability("ignoreProtectedModeSettings", true); 
 ieCapabilities.setCapability("disable-popup-blocking", true); 

 ieCapabilities.setCapability("enablePersistentHover", true); 

 ieCapabilities.setCapability("ignoreZoomSetting", true); 

 // Initialize the driver instance with IE Browser by passing Desired Capabilities Object 
 driver=new InternetExplorerDriver(ieCapabilities); 

Step 4:  Launch the browser and Maximize the window and Apply the implicit wait

//Open the Browser 
 driver.get("https://accounts.google.com/signin"); 
   
  // Maximize the Window 
 driver.manage().window().maximize(); 
 // Apply implicit wait 
 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); 

Step 5: Enter the correct gmail id and proceed to the password screen.

// Enter the correct gmail id 
 driver.findElement(By.xpath("//input[@type='email']")).sendKeys(""); 
 
 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 

Step 6: Enter the wrong password and verify the error message.

// ENter the wrong Password 
 driver.findElement(By.xpath("//input[@name='password']")).sendKeys("passeord"); 

 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 

 String erro_message=driver.findElement(By.xpath("//div[@jsname='B34EJ']/span")).getText(); 
 System.out.println(erro_message); 

 if(erro_message.contains("Wrong password")) {  
 System.out.println("Unable to login, Please enter the correct Password"); 
 } 

Complete code in Eclipse:

Explanation of the code:  Hereafter entering the password, the Error message will populate. So we are storing the wrong password text message in a web element and verifying it. If it contains the string ‘Wrong Password” then Script will print the error message “ Unable to login, Please enter the correct password”.

Output of the script:

Test Case 6: Check Functionality with valid and invalid inputs (Positive and Negative Testing)

Scenario: After entering invalid input on how to pass correct data, this is also a very important part while writing Selenium Test Script. In this code, you will learn How to correct incorrect data if entered by mistake. Let's have a look to code

Step1: Open your Eclipse and Create a new Project in the Selected Workspace.

Step 2: Create a new class with the name “VerifyWithValidInvalidInput”.

Step 3: Set the Browser Property on which browser you want to run the script

//Create a variable of WebDriver 
 WebDriver driver; 
 
// To run the script set the path for chrome driver 

 System.setProperty("webdriver.chrome.driver", ".\\driver\\chromedriver.exe"); 
 // Initialize the driver instance with Chrome Browser 
 driver=new ChromeDriver(); 

Step 4: Launch the browser and Maximize the window and Apply the implicit wait

//Open the Browser 
  driver.get("https://accounts.google.com/signin"); 
     // Maximize the Window 

 driver.manage().window().maximize(); 

 // Apply implicit wait 

 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); 

Step 5: Fill the gmail registration page with invalid First Name and Last Name

 driver.findElement(By.xpath("//span[contains(text(),'Create account')]")).click(); 

 Thread.sleep(1000); 
 driver.findElement(By.xpath("//div[contains(text(),'For myself')]")).click(); 

 driver.findElement(By.xpath("//input[@type='text' and @aria-label='First name']")).sendKeys("cavipinbansal11"); 

 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Lastname']")).sendKeys("cavipinbansal11123"); 

 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Username']")).sendKeys("cavipinbansal11123"); 
 driver.findElement(By.xpath("//input[@type='password' and @aria-label='Password']")).sendKeys("cavipinbansal111@1"); 
 .findElement(By.xpath("//input[@type='password' and @aria-label='Confirm']")).sendKeys("cavipinbansal111@1"); 

 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 

Step 6: Verify the error message coming after entered the wrong First Name and Last Name

String Expected_Error="Are you sure that you've entered your name correctly?"
 String Actual_Error=driver.findElement(By.xpath("//div[contains(text(),'Are you sure')]")).getText(); 
 System.out.println(Actual_Error); 

Step 7: Verify if error message is coming then enetered the correct First Name and Last Name

if(Actual_Error.contentEquals(Expected_Error)) { 
 System.out.println("error message came"); 
 driver.findElement(By.xpath("//input[@type='text' and @aria-label='First name']")).clear(); 
 driver.findElement(By.xpath("//input[@type='text' and @aria-label='First name']")).sendKeys("Divyanshi"); 

 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Last name']")).clear(); 
 driver.findElement(By.xpath("//input[@type='text' and @aria-label='Last name']")).sendKeys("Bansal"); 
 driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click(); 
 }

Step 8: Verify the next page coming after enetered the valid data

WebDriverWait wait=new WebDriverWait(driver,10); 
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@jsname='paFcre']/div/h1[@class='sfYUmb']"))); 
 String next_screen=driver.findElement(By.xpath("//div[@jsname='paFcre']/div/h1[@class='sfYUmb']")).getText(); 
 System.out.println(next_screen); 

 if(next_screen.contains("Verifying your phone number")) { 
 
 System.out.println("Registration successfully using gmail entered"); 
 
 } 

 else { 
 System.out.println("Please eneter correct email id or password"); 
 } 
 

Complete code in Eclipse :

Explanation of Code: Here you can see, first entered the invalid data for First Name and Last Name and due to this error message is coming. Then Store this error message in a String Variable and then verify this error message with Expected error message. If Error message matched then pass the valid data and go to the next page.

Output of the code:

Test Case 7: Check communication between different browsers

Scenario: When you need to verify your script on different browsers then this is very important to write Test Script in such a way that script could handle multiple browsers. This concept is also known as Cross Browser Testing. I have created a separate blog on this. You can visit that blog to get all the information.

Script in Eclipse to handle Multiple Browsers:

fbicons FaceBook twitterTwitter google+Google+ lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

6 days 27 Apr 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

-1 day 20 Apr 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

6 days 27 Apr 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

-1 day 20 Apr 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

6 days 27 Apr 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

5 days 26 Apr 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

4 days 25 Apr 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

-1 day 20 Apr 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

13 days 04 May 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

6 days 27 Apr 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

40 days 31 May 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

-1 day 20 Apr 2024

Search Posts

Reset

Receive Latest Materials and Offers on Selenium Course

Interviews