Learn Java For Automation Testing

Learn Java For Automation Testing
We at khawarautomationLabs, having a team of experts to always write for you. Our main objective is to provide free and valuable content of software testing to our readers. Our experts always try to write by following industry trends.

Learn Automation Testing, and Be the Best.

Learn Automation Testing, and Be the Best.
People can learn, by sitting in your drawing rooms, they don't need to go to any institution.

Do You Love Testing? Come & Join the Largest Testing Network

Do You Love Testing? Come & Join the Largest Testing Network
We at khawarautomationLabs, having a team of experts to always write for you. Our main objective is to provide free and valuable content of software testing to our readers. Our experts always try to write by following industry trends.

Let's Develop a Strategy to Automate the Things

Let's Develop a Strategy to Automate the Things

Latest Posts

TestNG Tutorial : How to use TestNG annotations in Selenium?

The Hacks of The Day


Hey folks, In this article I'm going to cover the most important topic that is called TestNG Framework. In this article, we will cover the following topics

  1. Introduction to TestNG
  2. How to integrate TestNG with selenium?
  3. How to add TestNG into your project?
  4. How to use different annotations in TestNG?

1. Introduction to TestNG

TestNG is a unit testing framework for Java programming language and NG stand for Next Generation. It is also called the Java unit testing framework. It is a very famous framework used by the developers to test the code. When developers develop some code, they test their code at the class level with the help of the TestNG framework. It is also used by AUtomation Engineers to design the test cases. They can integrate it with selenium. It is a very powerful tool, it gives a lot of options and features to design your test cases. It can also generate HTML reports. The purpose of TestNG is to design the test cases in a systematic way. Here are some key features
  • Open source, free to use
  • Available in the form of jar files
  • Only applicable with Java
  • Generate very good HTML reports
  • Supports a lot of annotations
  • Manage the sequence of test cases
  • Manage priorities of test cases 
  • Manage test cases dependencies
  • Manage test cases grouping
The most important feature is the data provider. You can execute your test case multiple times with different sets of data by using a data provider. To execute the same test cases again and again with a different set of data TestNG provides the amazing feature which is called data provider. Suppose you want to test the login functionality with different user names and passwords, you can use this feature. With data provider, you can read data from excel sheets.

Whenever automation engineers design an automation framework they must use the TestNG because of its rich support in designing the test cases. So in another form, it is also called TDD framework. TDD means Test Driven Development. In TDD tests are written before writing the actual code. Developers write the tests first before implementing the actual code. Developers use TestNG for unit testing.

When you join a new company and you have a fresh project to start the automation framework from scratch, you can use TestNG to design the test cases in a systematic way.

2. TestNG Integration with Selenium

Now let's start from scratch, how to download and install TestNG in Eclipse. For this, you can visit the following article which will explain in detail how to install TestNG in Eclipse.
How To Download And Install TestNG In Eclipse For Selenium WebDriver

3. Add TestNG into Your Project

Now let's see how to add the TestNG library into your project. The following steps are needed to add TestNG into your project

Step 1)
  1. Right-click on your project
  2. Click on Properties


Step 2)
  1. Click on Java Build Path
  2. Click on Add Library


Step 3)
  1. Select the library TestNG
  2. Click on Next button

















Step 4)
  1. Click on Finish button

















Step 5)
  1. Click on Apply and Close button
Step 6)
  1. Go to your project
  2. Check the TestNG folder
  3. As shown in the below image

















4. Annotations in TestNG

Now let's try to explore how automation engineers design test cases with the TestNG framework. What are the different annotations which are used to design test cases? Let's create a separate project as I have created "TestNGBasics" for demonstration purposes.

Remember one thing while creating a class doesn't select the main method because in TestNG we don't' need the main method to run the class. TestNG automatically executes the class. We never work with the main method in the TestNG class.













After creating a class let's try to write the selenium code with annotations. First, we explore what different annotations are available in TestNG.

TestNG provides different kinds of annotations. Every annotation is associated with one method. Annotations always start with @. In TestNG class, we simply write Java code with some other features provided by TestNG in the form of annotations. So when have you ever seen that some code is starting with "@" it means that is an annotation. In the TestNG framework, we will explore the following annotations.

  • @BeforeSuite
  • @BeforeTest
  • @BeforeClass
  • @BeforeMethod
  • @Test
  • @AfterMethod
  • @AfterCLass
  • @AfterTest
  • @AfterSuite

Given below is a demo example of TestNG annotations. This example is showing the use and sequence of annotations.
package com.test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestNGBasics {
 @BeforeSuite
 public void setUp() {

  System.out.println("Set system properties for chrome");
 }
 @BeforeTest
 public void launchBrowser() {
  System.out.println("Launch chrome");
 }
 @BeforeClass
 public void enterUrl() {
  System.out.println("Enter URL");
 }
 @BeforeMethod
 public void login() {
  System.out.println("Login to app");
 }
 @Test
 public void testTitle() {
  System.out.println("Title test");
 }
 @AfterMethod
 public void logOut() {
  System.out.println("Log out from app");
 }
 @AfterClass
 public void closeBrowser() {
  System.out.println("Close Browser");
 }
 @AfterTest
 public void generateReport() {
  System.out.println("Delete Cookies");
 }
}
The output is here
Output:
Set system properties for chrome
Launch chrome
Enter URL
Login to app
Google title test
Log out from the app
Close Browser
Delete Cookies
A TestNG class has three sections. The first section is the preconditions section, test case, and postconditions.
  • Pre-Conditions
  • Test Cases
  • Post-Conditions
The annotations that start with @Before keyword come into the pre-conditions section. The second section contains the @Test annotation. The third section contains the annotations that start with @After keyword. The most important thing is the sequence of annotations. You should be familiar with the sequence of annotations. As you can see the sequence in the below diagram.































In the above example, we have executed only one test case. Now let's see the scenario for more than one test case. If we add the following one more test case in the above example, the output will be a little bit different in terms of annotations sequence.

public class TestNGBasics {
 @BeforeSuite
 public void setUp() {
  System.out.println("Set system properties for chrome");
 }
 @BeforeTest
 public void launchBrowser() {
  System.out.println("Launch chrome");
 }
 @BeforeClass
 public void enterUrl() {
  System.out.println("Enter URL");
 }
 @BeforeMethod
 public void login() {
  System.out.println("Login to app");
 }
 // Test Case 1
 @Test
 public void testTitle() {
  System.out.println("Title test");
 }
 Test Case 2
 @Test
 public void searchTest() {
  System.out.println("Search test");
 }
 @AfterMethod
 public void logOut() {
  System.out.println("Log out from app");
 }
 @AfterClass
 public void closeBrowser() {
  System.out.println("Close Browser");
 }
 @AfterTest
 public void generateReport() {
  System.out.println("Delete Cookies");
 }
}
The following is the output of the code
Output:
Set system properties for chrome
Launch chrome
Enter URL
// Test Case 2
Login to app
Search test
Log out from the app
// Test Case 1
Login to app
Title test
Log out from the app
Close Browser
Delete Cookies
Remember one thing, the two annotations @BeforeMethod and @AfterMethod are executed for every test case. Suppose if you have n number of test cases, then these annotations will be executed n times. One more thing in the above output that is the test case 2 is executing first then test case 1. The reason is that TestNG executes the tests alphabetically. We can also set the priorities for test cases which we will cover in the next section. 

Now let's try to write the selenium code with TestNG annotations. In the following example, you will also learn how to control the execution of test cases by using priorities. Suppose you have n number of the test case, you can set the priority of each test case. Based on these priorities execution will happen.

package com.test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class GoogleTest {
 public String baseUrl = "http://google.com";
 public WebDriver driver;
 @BeforeMethod
 public void launchBrowser() {
  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  driver = new ChromeDriver();
  driver.get(baseUrl);
 }
 @Test(priority = 1)
 public void googleTitle() {
  String expectedTitle = "Google";
  String actualTitle = driver.getTitle();
  Assert.assertEquals(actualTitle, expectedTitle);
 }
 @Test(priority = 2)
 public void logoTest() { 
  // Please write the logic here
 }
 @AfterMethod
 public void close() {
  driver.close();
 }
}

Mostly the three annotations (@BeforeMethod, @Test, @AfterMethod) are used in TestNG. In t above example, we have used priority to control the execution of test cases. Priority 1 means this test case will be executed first then priority 2 and so on. I hope this article will make sense for you guys so far we have covered. In the next article, we will cover the @dataprovider annotation, HTML report some other stuff related to TestNG.

How to Download and Install TestNG in Eclipse for Selenium WebDriver

The Hacks of The Day
Install testng in eclipse

Guys In this article I will let you know how to download and install TestNG in Eclipse for Selenium WebDriver. Following is a step by step guide to install TestNG in Eclipse IDE.

Installation Process

Step 1) 
  1. Go to https://www.google.com/
  2. Type "testng" in the search field.
  3. Click on the "Google Search" button.
  4. Open the first link from the search results.

Step 2) 
  1. TestNG documentation page will be loaded.
  2. To locate the TestNG plugin press ctr+f and type "eclipse".
  3. Now press Enter until you find the plugin link.
  4. After locating the link("Eclipse-plugin") click on it. 

Step 3) 
  1. The landing page will show the plugin versions.
  2. Copy the downloading link for the latest release.
  3. But try to copy the link that is compatible with your eclipse version.
  4. In my case, I am using this one https://dl.bintray.com/testng-team/testng-eclipse-release/7.2.0/

Step 4) 
  1. Launch Eclipse IDE.
  2. Click on the "Help" menu.
  3. Click on the "Install New Software..." option.

Step 5) 
  1. Eclipse install dialog box will show.
  2. Click on the "Add" button.

Step 6) 
  1. Add repository dialog box will show.
  2. Enter TestNG in Name field.
  3. Enter the copied URL in the Location field (Copied in step 3).
  4. Click on the "Add" button.

Step 7) 
  1. Select the "TestNG" checkbox.
  2. Click on the "Next" button.

Step 8) 
  1. Component review dialog will show.
  2. Click on the "Next" button.

Step 9) 
  1. Click on radion button "I accept the terms of the license agreement".
  2. Click on the "Finish" button.

It will take some time to install the plugin, the speed of installation depends on your internet speed. After some time it will prompt a security warning.

Step 10) 
  1. When you see a security warning just click on the "Install Anyway" button.

Step 11) 
  1. Wait for the installation to finish. after some time a popup will open, then click on "Restart Now." button

Step 12) 
  1. After the restart, verify either TestNG is installed or not. 
  2. For verification navigate to Window > Show View > Other.
  3. A directory box will show.
  4. Open the "Java" directory and see if TestNG is there.

Above mentioned is the complete process of TestNG installation in Eclipse. If you have any queries, please comment below. Like this post, don’t forget to share it.

    Mouse Hover, Drag and Drop in Selenium WebDriver

    The Hacks of The Day
    Mouse Hover, Drag and Drop in Selenium WebDriver

    In this article, you will learn how to use mouse hover, drag and drop features in selenium web driver. Mouse hover is basically an action when you hover the mouse over a particular area, it shows a list of sub-menu. In the following diagram you can see when we hover on "Contribute", a list is shown. In selenium to handle such type of menu, we use the "Actions" class. We can not click directly on any entry in the list, if we try to click on any language, an exception will raise "Unable To Locate Element". To overcome this problem selenium has provided an Actions class. So before going into coding details, first we see what is Actions class and what it does?


    What is Actions Class:

    A class in the Selenium library is used to handle the mouse events, keyboard events, drag and drop and click on multiple elements using the advanced user interactions API. In Actions class, we have the following most commonly used keyboard and mouse events.

    1) moveToElement(toElement)
    2) clickAndHold(Webelement)
    3) contextClick()
    4) doubleClick()
    5) dragAndDrop(source, target)
    6) dragAndDropBy(source, xOffset, yOffset)
    7) release()

    Let's try to explain some of them that are used frequently in real-time projects.

    1) Mouse Movement (moveToElement())

    It is used to hover on the designated area. Because without hover we can not click on the submenu items. Let's try to understand this concept by writing the code with Actions class. If you want to click on the sub-element, first we need to mouse hover on the parent-element like "Contribute" as shown in the above image. then we can click on sub-element. Given below example will show the real-time result.

    Scenario:

    1) Go to https://jqueryui.com/
    2) Move mouse on Contribute link with Action class
    3) Click on CLA

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    public class MoveToElement {
     public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://jqueryui.com/");
      driver.manage().window().maximize();
      Actions actions = new Actions(driver);
      WebElement contributeLink = driver.findElement(By.xpath("//a[contains(text(),'Contribute')]"));
      actions.moveToElement(contributeLink).perform();
      System.out.println("Mouse Hover on Contribute");
      Thread.sleep(1000);
      driver.findElement(By.xpath("//a[contains(text(),'CLA')]")).click();
      System.out.println("Clicking on CLA");
     }
    }
    
    In the above example, we have created an object of an Actions Class passing the WebDriver instance. With the object of the Actions class, the driver moves to the main menu and then to the sub-menu and click on it.

    2) Drag and Drop (clickAndHold(Webelement))

    In Drag and Drop, we hold the source element and place it on the target element. For this, we use clickAndHold(webelement) method. It holds the left click button down on the specified element. When the source element is moved on the target element then we release the left click by using the release() method. For practice purposes, you can run the following code snippet

    Scenario:

    1) Go to https://jqueryui.com/droppable/
    2) Hold the source element with clickAndHold() method
    3) Move the source element on the target element
    4) Release the source element

    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    public class ClickAndHoldMethod {
     public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://jqueryui.com/droppable/");
      driver.manage().window().maximize();
      driver.switchTo().frame(0);
      Actions actions = new Actions(driver);
      actions.clickAndHold(driver.findElement(By.xpath("//div[@id= 'draggable']")))
             .moveToElement(driver.findElement(By.xpath("//div[@id= 'droppable']")))
             .release().build().perform();
     }
    }

    Alternative Method (dragAndDrop(scr element, target element))

    Alternatively, you can do drag and drop by using dragAndDrop(sourceElement, targetElement) method. In this method we need to pass the two parameters, one is source element and the other is the target element.

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    public class DragAndDropMethod {
     public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://jqueryui.com/droppable/");
      driver.manage().window().maximize();
      driver.switchTo().frame(0);
      Actions actions = new Actions(driver);
      WebElement sourceElement = driver.findElement(By.xpath("//div[@id= 'draggable']"));
      WebElement targetElement = driver.findElement(By.xpath("//div[@id= 'droppable']"));
      actions.dragAndDrop(sourceElement, targetElement).build().perform();
     }
    }
    

    3) Drag and Drop (dragAndDropBy(source, xOffset, yOffset))

    If you want to move a single element to a new location then dragAndDropBy(source, xOffset, yOffset) method is used. It takes two parameters one is source element and the other one is x,y coordinates. In the given example the source element will be moved to a new location (xOffset = 200,yOffset = 100).
    Selenium Command: actions.dragAndDropBy(elementToDrag, 200, 100).perform();
    

    Example Code:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    public class DragAndDropBy {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://jqueryui.com/draggable/");
      driver.manage().window().maximize();
      driver.switchTo().frame(0);
      WebElement elementToDrag = driver.findElement(By.id("draggable"));
      Actions actions = new Actions(driver);
      actions.dragAndDropBy(elementToDrag, 200, 100).perform();
     }
    }
    

    4) Double Click (doubleClick())

    Double click action in Selenium web driver can be achieved by using Actions class. Actions class is a builtin class in Selenium web driver used to perform multiple keyboard and mouse operations such as Right Click, Drag and Drop. Double click in Selenium using Actions class is done by the following selenium command.
    Actions actions = new Actions(driver);
    WebElement element = driver.findElement(By.id("ID"));
    actions.doubleClick(element).perform();
    
    
    Initially, we instantiate an object of Actions class and pass the driver object as a parameter. Then we locate the required element that we want to double click. After that, we use the pre-defined method doubleClick() to perform the double click action. Given below is the practical example of double click method.
    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    public class DoubleClick {
     public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://jqueryui.com/");
      driver.manage().window().maximize();
      Actions actions = new Actions(driver);
      actions.moveToElement(driver.findElement(By.xpath("//h3[text()= 'Interactions']")));
      actions.doubleClick().perform();
     }
    }
    
    I hope this article, will help you more to understand the Mouse Events, Drag and Drop events.

    How to Handle Frames in Selenium WebDriver

    The Hacks of The Day

    Today I'm going to cover one very important topic in Selenium WebDriver how to handle different frames in Selenium WebDriver. Sometimes you see that you are unable to locate an element and sometimes you see that element not found exception so there is a very big reason behind that, that might be possible that element is available on that particular frame so what is a frame? First, we need to understand it.

    What is Frame?

    A frame is a part of the web page, which displays contents independently, means independent of its container. With the help of the following image, you can understand easily, what is a frame and how it works. Whenever you open any browser and type the URL in the address bar what happens, a web page is loaded against that particular URL. That page contains different web elements like you know these elements are text fields, radio buttons, checkboxes, and some links are available or some images are available, number of elements are directly available on the page.


    But some elements are available in the particular frame so one more hierarchy is their frame. So the first hierarchy I would say the opening of browser and then we have a page that is your web page, which you open in the browser like Facebook.com, Twittwe.com or whatever and the third hierarchy is called a frame. Now what exactly the frame, a frame is another web element, it will be treated as a web element but it will also contain a number of elements as shown in the diagram, in this frame also we have some buttons or links, buttons and text fields.

    So in simple words, some elements on web pages are available in the form of frames, when the user clicks or hovers on that element, a frame is shown that frame also has some web elements. The question is here, how do we interact with frame and how we have access to the frame elements. Frame elements mean those elements which are available on that particular frame.

    How to access the elements in a frame?

    To access the frame elements we have to switch from page to frame, then we can access frame elements. Otherwise, you will get an exception "NoSuchElementFound". The
    the general syntax to switch over elements in a frame is:
    driver.switchTo().frame();
    
    There are two important properties that are used to switch over the elements in the frame.

    1) By Index
    2) By Name

    By Index:

    The frame index always starts from 0. If you want to interact with the first frame, you can use the following Selenium command.
    driver.switchTo().frame(0);
    
    Similarly, you can get control of other frames by using the index number. For the second frame, you can write the following command, and so on.
    driver.switchTo().frame(1);
    

    By Name:

    Name is another property that you can use to access the frame elements.
    driver.switchTo().frame("myframe");

    Example Code

    Scenario:

     1) Go to this URL https://chercher.tech/practice/frames-example-selenium-webdriver
     2) Switch to frame
     3) Find the element in the frame
     4) Enter some text
     I have found one very good example of a frame. Let's see how it works practically.
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class FrameHandling {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://chercher.tech/practice/frames-example-selenium-webdriver");
      driver.manage().window().maximize();
      driver.switchTo().frame("frame1");
      driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Sample Input");
     }
    }

    Nested Frame

    Nested frames are used to navigate from frame to another frame. In our example let's try to tick the checkbox. A checkbox is an element of frame 3, which resides inside the frame 1. So to interact with the checkbox first we need to switch to frame 1. Then we can switch to frame 3. But directly we can't access frame 3. The given image is showing the nested frame process.


    Scenario: 

    1) Launch the URL https://chercher.tech/practice/frames-example-selenium-webdriver
     2) Switch to frame1
     3) Switch to frame3
     4) Tick the checkbox

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class NestedFrames {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://chercher.tech/practice/frames-example-selenium-webdriver");
      driver.manage().window().maximize();
      driver.switchTo().frame("frame1");
      driver.switchTo().frame("frame3");
      WebElement checkbox = driver.findElement(By.xpath("//input[@type='checkbox']"));
      if (!checkbox.isSelected()) {
       checkbox.click();
      }
     }
    }
    

    Switch to Parent Frame

    To get out of the current frame the following command is used. It moves the control to the outer frame or page level. If you don't shift the control to the parent frame, you can't access the other elements.
    driver.switchTo().parentFrame()
    
    Now let try to move from frame 3 to frame1 then to the page level. As shown in the below diagram.


    Scenario:

     1) Tick the checkbox in frame 3, frame 3 is present in frame 1
     2) Move back to frame 1 then enter some text in the topic field
     3) Now get out of frame 1 to page level and compare the header title
    import org.openqa.selenium.By;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class ParentFrame {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      driver.get("https://chercher.tech/practice/frames-example-selenium-webdriver");
      driver.manage().window().maximize();
      driver.switchTo().frame("frame1");
      driver.switchTo().frame("frame3");
      WebElement checkbox = driver.findElement(By.xpath("//input[@type='checkbox']"));
      if (!checkbox.isSelected()) {
       checkbox.click();
      }
      driver.switchTo().parentFrame();
      driver.findElement(By.xpath("//input[@type='text']")).sendKeys("selenium");
      driver.switchTo().parentFrame();
      String textValue = driver.findElement(By.xpath("//label/span")).getText();
      if (textValue.equals("selenium webdriver")) {
       System.out.println("Topic value is equal to 'selenium webdriver'");
      } else {
       System.out.println("Text is not equal to header text");
      }
     }
    }
    

    Default Content

    The default Content command exits all the frames and moves the selenium control to the page level. You can directly move to page-level from any frame. The following syntax is used for default content:
    driver.switchTo().defaultContent();
    

    Summary:

    1) How to switch to frame in selenium
     2) How to interact with frame elements
     3) How to use nested frames
     4) How to move the control to page level
     5) How to use the parent frame

    How to Handle Alerts in Selenium WebDriver

    The Hacks of The Day

    In this tutorial, we will let you know about different types of alert appeared in web applications and how to handle these Alerts in Selenium WebDriver. We will also figure out how do we accept and reject the alert depending upon the alert types. Alert is a small pop up window that comes up on the screen. There are numerous user activities that can bring about an alert on-screen. For e.g. user clicked on a button that displayed a message, The HTML page asked you for some extra information. So in this article, we will learn how to Handle Alerts, JavaScript Alerts, and PopUp Boxes in Selenium WebDriver.

    What is Alert?

    An alert is a small dialog box that displays on-screen. It gives some kind of information to the user or asks for permission to perform a certain kind of operation. It can be also used for warning purposes. Alerts are different from regular windows. The major difference is that alerts are blocking in nature, they will not allow any action on the underlying webpage if they are present.

    How to handle Alert in Selenium WebDriver

    Selenium WebDriver provides the following methods to interact with the Alerts depending on the Alert types.

    1. void dismiss(): It is used to cancel the alert
    driver.switchTo().alert().dismiss();

    2. void accept(): It is used to click on ok button of the alert
    driver.switchTo().alert().accept();

    3. String getText(): It captures the alert message text
    driver.switchTo().alert().getText();

    4. void sendKeys(String stringToSend): It sends some data to alert
    driver.switchTo().alert().sendKeys("Text");

    1. Simple alert

    Simple alerts have just the ok button on them, they give some information to users. Following is the practice example of a simple alert in Selenium Webdriver.

    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class SimpleAlertBox {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      // Launch the URL
      driver.get("https://www.testandquiz.com/selenium/testing.html");
      driver.manage().window().maximize();
      driver.findElement(By.xpath("//button[text()='Generate Alert Box']")).click();
      // First Alert class will shift the focus to the alert box
      Alert alert = driver.switchTo().alert();
      // Accept() method will accept the alert box
      alert.accept();
      // Close the browser
      driver.close();
     }
    }
    

    2. Confirmation Alert

    Confirmation Alert comes with two options (Ok/Cancel), you can accept it or dismiss it. It requires user confirmation to perform some task. Users can accept it or cancel it. Here is a code to dismiss the confirmation alert.
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class ConfirmationAlert {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      // Launch the URL
      driver.get("https://www.testandquiz.com/selenium/testing.html");
      driver.manage().window().maximize();
      driver.findElement(By.xpath("//button[text()='Generate Confirm Box']")).click();
      Alert confirmationAlert = driver.switchTo().alert();
      confirmationAlert.dismiss();
      // Close the browser
      driver.close();
     }
    }
    

    3. Prompt Alert

    In the prompt alert, you can enter some text by using sendkeys method. These alerts are used when some information is required from the user side. Here is the code example for the prompt alert.
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class PromptAlert {
     public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
      WebDriver driver = new ChromeDriver();
      // Launch the URL
      driver.get("https://www.khawarautomationlabs.com/2020/04/alerts-in-selenium-webdriver-in-this.html");
      driver.manage().window().maximize();
      driver.findElement(By.xpath("//button[text() = 'Click on me']")).click();
      Alert promptAlert = driver.switchTo().alert();
      String alertText = promptAlert.getText();
      System.out.println("Alert text is: " + alertText);
      promptAlert.sendKeys("Prompt Alert");
      promptAlert.accept();
     }
    }
    Prompt popup Sample

    Prompt Box Example

    Prompt Box Click the button to open the prompt box.

    How to Click on Image in Selenium Webdriver

    The Hacks of The Day

    In this tutorial, we will let you know how to click on an image in Selenium WebDriver. When a user clicks on an image it redirects the user to a different window or page. As shown in the below image, when the user clicks on the "Facebook" logo, it redirects to the homepage.


    We can't find image elements by By.linkText() and By.partialLinkText() methods because image links basically have no link texts at all. In this case, we can use CssSelector or XPath.

    In the below example, we will access the "Facebook" logo on the upper left portion of Facebook's Password Recovery page.

    Scenario:
    1. Go to this URL https://www.facebook.com/login/identify?ctx=recover
    2. Click on Facebook logo
    3. The home page will show
    1) Click on image By using XPath
    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class ClickOnImageByXpath {
     public static void main(String[] args) {
      String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
      System.setProperty("webdriver.gecko.geckodriver",
      "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver");
      FirefoxDriver driver = new FirefoxDriver();
      driver.get(baseUrl);
      driver.findElement(By.xpath("//a[@href  = 'https://web.facebook.com/']")).click();
      if (driver.getTitle().equals("Facebook – log in or sign up")) {
       System.out.println("We are at Facebook's homepage");
      } else {
       System.out.println("We are not at Facebook's homepage");
    }
    
    2) Click on image By using CssSelector
    import org.openqa.selenium.By;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class ClickOnImageByCssSelector {
     public static void main(String[] args) {
      String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
      System.setProperty("webdriver.gecko.geckodriver",
      "/home/khawer/eclipse-workspace/TrainingVideos/geckodriver");
      FirefoxDriver driver = new FirefoxDriver();
      driver.get(baseUrl);
      driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]")).click();
      if (driver.getTitle().equals("Facebook – log in or sign up")) {
       System.out.println("We are at Facebook's homepage");
      } else {
       System.out.println("We are not at Facebook's homepage");
      }
     }
    }