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");
      }
     }
    }
    

    How to access forms in Selenium with Java

    The Hacks of The Day

    Have you noticed the ubiquity of web forms while surfing the internet? Almost every website or web-application you visit has an interface in the form of web-forms to collect the necessary information about yourself. A webform comprises web elements such as checkbox, radio button, password, drop down to collect user data.

    If you are going to perform automated browser testing for your website or web-application then you simply can’t afford to drop-out the forms from your test automation scripts. In the case of test automation, Selenium has an API (Application Programming Interface) that helps to find these web elements and take subsequent actions on them like selecting a value or entering some text.

    This article will help you to understand how you can access web forms in Selenium to automate the web application. I will be using the JUnit Framework with some annotations to execute our Selenium automation testing later in this article.

    To begin our learning with, we’ll first understand what a WebElement is, how can it be accessed in Selenium Automation, and then go about seeing the basic form elements like the input boxes, buttons, the actions that can be performed on these forms and finally writing a script to handle a form and run it on various browsers. If you are already aware of the basics then feel free to skip through the sections according to yourself:

    What Is A WebElement?

    In simple words, anything present on a webpage constitutes a WebElement. Examples can be a text box, a radio button, etc. Selenium Webdriver provides an interface that is called the WebElement which is responsible for all the possible actions that take place on the web page. To locate the web elements, the Selenium web driver provides the two methods which are given below

    1. findElement()
    2. findElements().

    findElement(): It locates the single web element. After finding the element is found it is returned as a WebElement object. Let us now see the syntax of findElement(), but before we start using the WebElement object in our test script we need to make note of one very important point.

    We need to import the following packages to start creating objects of the WebElements:

    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.WebElement;

    Syntax for findElement():
    WebElement ele = driver.findElement(By.id("id");

    WebElement ele = driver.findElement(By.xpath("xpath");
    findElements(): It returns a list of WebElements that corresponds to the locator defined in the method.

    The syntax for findElements() is as shown below:
    List<WebElement> ele = driver.findElements(By.xpath("xpath");

    Now that we are thorough with the understanding of the WebElement interface, along with the difference between findElement() & findElements() method in Selenium automation testing. It is time to deep dive into these web elements. We will now list down all the web fields that may be involved in your website or web application form. Now we will learn how to access web forms in Selenium WebDriver.

    How To Locate Web Elements

    Now we know that what different types of web elements we can come across in our application, We need to identify these web elements through our Selenium automation testing scripts and to do so first we need to find the locators. Locators are the parameters given to the findElement() or findElements() methods which help to retrieve the web element by using its properties like the ID, Name, Class, etc. In general, we have 8 locators in Selenium that are widely used:
    • ID
    • Name
    • Tag Name
    • Class Name
    • LinkText
    • Partial LinkText
    • XPath
    • CSS Selector
    Few of the examples are:

    WebElement eid = driver.findElement(By.id(“email”);

    WebElement pswd = driver.findElement(By.name(“password”);

    WebElement sbmtBtn = driver.findElement(By.xpath(“//input[@value=”submit”]”);

    Types of Fields

    To subsequently build the scripts to access forms in Selenium WebDriver, we need to understand the various fields that we will have to handle in our test automation scripts. Let's see how to access these Web elements using Selenium Web Driver with Java. Selenium represents the form element as an object of Web Element. It has an API to find the elements and take action on them like entering text into text boxes, clicking on the buttons, etc. Now we will explore the methods that Selenium makes available to access the form element. Let us try to dig a little more about these WebElements one by one.

    Input Box

    The input box is a primary element in any form. No form is complete without user input. It can be of two types:

    Text Field Box – Text boxes that display the value as is entered by the user.
    Password Field Box – Text boxes that display special characters (mostly ‘*’) when the value is entered by the user.
    The following image representing the input boxes inside a web form.


    Buttons

    Buttons are the most important fields to consider while you access forms for Selenium automation testing. There is no point in filling up a form if there is no interface to submit the same. Buttons are simply used to submit whatever information we have filled in our text boxes. This can be submitting some form of data or simply submitting the sign-in information to the server.

    CheckBox

    In most of the websites that are widely used we see a small box that enables us to check or uncheck it. Mostly in agreement sections wherein the user needs to confirm the understanding of these policies. The checkbox is used to return a boolean value, if it is checked then it would return True else would return false.


    Radio Button

    A radio button is shown in the form of a circle on any web page. Mostly it is used to show the "Gender" on sign up forms. That is what a radio button is. It is similar to a checkbox only difference being if we are given multiple radio buttons we can select just one, while in the case of multiple checkboxes, we can opt multiple of them.


    Link

    We all face the common problem of forgetting our account passwords. Noticed the Forgot Password link on the screens? That is what a link is. It redirects us to a new web page or a new window pop-up or a similar thing. It links us to a new URL altogether.

    Drop Down

    There are times for a website where there are multiple options for a specific category. Say a website to book your flight tickets. To pick up the Origin & Destination city we often see a list with multiple values. This list which has an arrow at the rightmost end to expand and show the values is called a drop-down. It provides a list of options to the user thereby giving access to one or multiple values as per the requirement.


    Below is a snapshot of the Facebook Sign up form.

    How To Interact With Web Elements

    Now, let's see how we access the forms elements in Selenium and how different actions can be performed on each one of them.

    Input Box

    To handle any input box, we must be able to enter information, clear information, or get information from the box. Selenium offers the following methods to work with text boxes are:

    • sendKeys()
    • clear()
    • getText()
    To enter text into a textbox we can use the sendKeys method which would input the user required text from our automation script.

    driver.findElement(By.id(“username”).sendKeys(“test@gmail.com”);

    The above statement would enter the Email ID as abc@gmail.com into a text box whose ID is username. Now, to clear a pre-entered text or the text that you last entered can be wiped clean with the clear() method.

    driver.findElement(By.id(“username”)).clear();

    The third method that can be used on a text box is the getText() method. It’ll fetch the text that is written in a text box in case we need to validate some existing or entered text.

    String nameText = driver.findElement(By.id(“username”)).getText();

    The above line of code would return the text, let us take the text entered by the first line of code above, i.e. test@gmail.com and store it in nameText variable of string type. There might be chances when the text is present in the value property. In such a scenario we will use the getAttribute() method in place of getText().

    String nameText = driver.findElement(By.id(“username”)).getAttribute(“value”);

     Buttons

    We can submit the information by using buttons. This can be done through click actions on the same. The following are the two methods that are available in selenium to perform actions on the buttons.
    • click()
    • submit()
    It might look like there is no difference in both the methods, but a very minute detail changes the usage of each method. Both of these methods would eventually submit the form data to the server, but we need to understand the type of the web element present. If the element type is either ‘submit’ or ‘button’, click() method would work for both, but if the element type is ‘submit’ with the button being inside

    driver.findElement(By.id(“submtLogIn”).click();

    driver.findElement(By.id(“submtLogIn”).submit();

    CheckBox

    To interact with checkbox, we’ll use the following Selenium methods:
    • click()
    • isSelected()
    To select or check a value we use the click() method. It simply changes the state from unchecked to checked and vice-versa.

    driver.findElement(By.id(“name”)).click();

    Now that we can check/uncheck a checkbox, we might first need to know the state of a checkbox before performing a certain action with Selenium automation testing. To get the state we use isSelected() method which would return a boolean value. This means if the checkbox is checked we’d get a True else we’ll get False.

    boolean state = driver.findElement(By.id(“name”)).isSelected();

    Radio Button

    The actions performed on the radio button are similar to those on a checkbox and we can use the same methods as above for the radio button as well.
    • click()
    • isSelected()

    Link

    Links are generally embedded in a web page for us to navigate to a new screen or a popup or a form. We can either do a click action on them or can get the text that it holds and then proceed with our execution.
    • click()
    • getText()
    Both of the above methods can be used in a way similar as stated above.

    Dropdown

    Dropdowns are very commonly and widely used for selecting among a range of options. There is a wide variety of methods that we can use with dropdowns. Let us see them and their corresponding syntax & usage one by one.

    selectByVisibleText(String)-  It selects the value from the dropdown by comparing it with visible text, that is passed as a parameter.

    selectByIndex(int)- Selects option based on the index in the drop-down menu with integer parameter passed as the index.

    selectByValue(String)- It selects the option in the dropdown, based on the value in string format.

    In a similar way we can deselect any selected value from the dropdown using any of the below options:

    deselectByVisibleText(String)
    deselectByIndex(int)
    deselectByValue(String)
    deSelectAll()

    To select an option from the dropdown in selenium, syntax can be as follows:

    Select se=new Select(driver.findElement(By.id("nation")));
    se.selectByValue("Ind");

    To select the single or multiple options some methods are given below:

    getAllSelectedOptions()- It is used to get the list of all selected option in the dropdown.
    getFirstSelectedOption()- This method would return the first option that has been selected from the dropdown and unlike the above method it would return a single web element and not a list.

    getOptions()- This method would enable us to get a list of all available options in a dropdown.

    isMultiple()- To check if a dropdown can take multiple options, we can use isMultiple() method which would return a boolean value.

    To get a list of options we can write our piece of code by referencing a list object:

    Select se=new Select(driver.findElement(By.id("nation")));
    List<WebElement> list=se.getOptions();

    Now let's try to perform the basic operations and handling of form elements.

    Working Example of Form Elements

    Here is a practical demonstration of the test script, how to access forms in Selenium.

    Facebook Sign up Script

    package com.qa.demo.testcases;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.Select;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;
    
    public class TestFaceBookForm {
    
     public static WebDriver driver;
    
     @BeforeClass
     public static void setUp() {
      //Launch FireFox Browser and Hit the URL
      System.setProperty("webdriver.gecko.driver","/home/khawer/Desktop/geckodriver");
      driver = new FirefoxDriver();
      driver.manage().window().maximize();
      driver.get("https://facebook.com");
     }
    
     @Test
     public void fillForm() {
    
      // Enter First Name
      WebElement fName = driver.findElement(By.xpath("//input[@name='firstname']"));
      fName.sendKeys("--Enter you name here--");
      
      // Enter Last Name
      WebElement lName = driver.findElement(By.xpath("//input[@name='lastname']"));
      lName.sendKeys("--Enter your last name--");
      
      // We are writing the following two lines just to check the clear function
      lName.clear();
      lName.sendKeys("XYZ");
      
      // Enter Email
      WebElement eMail = driver.findElement(By.xpath("//input[@name='reg_email__']"));
      eMail.sendKeys("--Enter mail or contact number--");
      
      // Enter Password
      WebElement pwd = driver.findElement(By.xpath("//input[@name='reg_passwd__']"));
      pwd.sendKeys("--Enter a valid password here--");
     
      // Select Method for drop downs
      Select date = new Select(driver.findElement(By.xpath("(id('day'))")));
      date.selectByVisibleText("25");
      
      Select month = new Select(driver.findElement(By.xpath("(id('month'))")));
      month.selectByVisibleText("Mar");
      Select year = new Select(driver.findElement(By.xpath("(id('year'))")));
      year.selectByVisibleText("1985");
     
      driver.findElement(By.className("_58mt")).click();
    
      WebElement sgnUp = driver.findElement(By.xpath("//button[@id='u_0_13']"));
      sgnUp.click();
     }
     @AfterClass
     public static void tearDown() {
      //driver.quit();
     }
    }
    

    Java Basics - Lecture 5 - What is Inheritance in Java?

    The Hacks of The Day














    Inheritance in Java

    A process in which one class utilizes the property of another class is called Inheritance. The class that's utilizing the property of another class is called a child class, and therefore the other is called parent class.

    It facilitates the code reusability so that a class has to write only the unique features and the rest of the common properties(Data Members) and functionalities(Member Functions) can be extended from another class. Child Class: The class that extends the features of another class is known as child class, subclass or derived class. Parent Class:

    The class whose properties and functionalities are inherited by another class is known as a parent class, superclass, or Base class. The process of defining a new class based on an existing class that extends its common data members and methods is called inheritance. Inheritance allows us to reuse code, it improves reusability in your java application.

    Note: The main advantage of Inheritance is code reusability, the code that is already present in base class need not be rewritten in the child class.

    Syntax: To inherit the properties of a class we use extends keyword. Here class B is child class and class A is parent class. Class B is inheriting the properties and methods of Class A.
    class B extends A
    {  
    }  
    

    Inheritance Example: 

    In the following example, we have a base class Shape and a subclass Circle. Since class Circle extends the width and height properties and area() method from the base class, we need not declare these properties and methods in the subclass. Here we have width, height, and area() method which are common to all the shapes so we have declared them in the base class, this way the child classes like Circle, Rectangle and Triangle do not need to write this code and can be used directly from the base class.
    class Shape {
       int width = 20;
       int height = 30;
       public void area(){
        System.out.println("Shape");
       }
    }
    class Circle extends Shape{
        double radius = 40;
        public static void main(String args[]){
        Circle obj = new Circle();
        System.out.println(obj.width);
        System.out.println(obj.height);
        System.out.println(obj.radius);
        obj.area();
       }
    }
    
    Output:
    20
    30
    40
    Shape
    
    So based on the above example we can say that Circle IS-A Shape. In Java, a child class has an IS-A relationship with the parent class. This is inheritance is known as the IS-A relationship between the child and parent class.

    Important Note!! 

    The derived class can inherit all the data members and member functions that are declared as public or protected. If the data members or member functions of the superclass are declared as private then the derived class cannot use them directly. The private members are only accessible in its own class. To access private members out of class, getter and setter are used.

    Types of Inheritance:

    There are different types of inheritance in Java:

    1. Single inheritance
    2. Multiple inheritances
    3. Multilevel inheritance
    4. Hierarchical Inheritance
    5. Hybrid Inheritance


    Single inheritance: In single inheritance, a derived class is created from one parent class. It refers to a child and parent class relationship where a class extends another class. Syntax:
    //Parent Class
    class Parent 
    {
       //methods and fields  
    }
    //Child Class
    class childClass extends Parent
    {  
       //methods and fields  
    }
    
    Let's take an example. Suppose we have a parent class "Vehicle" and child class "Car". Child class will acquire the features of the parent class. As shown in the main method we have created an object of the child class, this object will call the methods of both classes (Child & Parent)
    class Vehilce {
     public void engine() {
      System.out.println("engine...");
     }
    }
    class Car extends Vehicle {
     public void start() {
      System.out.println("start...");
     }
    }
    public class ExecuteClass {
     public static void main(String args[]) {
      Car c = new Car();
      c.engine();
      c.start();
     }
    }
    
    Multiple inheritances: In multiple inheritance one class extending more than one class, which means One child class has two parent classes. As per the above diagram, Class C extends Class A and Class B both.

    Multilevel inheritance: In multilevel inheritance, one class can inherit from the child class. Hence, the child class becomes the parent class for the new one. As shown in the below diagram Class C is a child of Class B and B is a child class of Class A.

    Hierarchical Inheritance: In hierarchical inheritance, more than one classes extend one class. In the below diagram Class B, C, and D inherit the same class A.

    Hybrid Inheritance: Hybrid inheritance is a combination of Single and Multiple inheritances in a single program. As per the below example, all the public and protected members of Class A are inherited into Class D, via Class B and Class C.

    Note: Java doesn't support hybrid/Multiple inheritances

    Constructors and Inheritance: 

    When you create an object of a child class, it's constructor is called, it by default invokes the superclass class default constructor. In inheritance, constructors are called in a top-down approach.

    A SuperClass constructor is called by using super keyword. The super keyword refers to the superclass, immediately above the calling class in the hierarchy. To access the data members or methods of the parent class super keyword is used.
    class ParentClass{
       //Parent class constructor
       ParentClass(){
        System.out.println("Constructor of Parent");
       }
    }
    class ChildClass extends ParentClass{
       ChildClass(){
        
        System.out.println("Constructor of Child");
       }
       public static void main(String args[]){
        //Creating the object of child class
        new ChildClass();
       }
    }
    
    Output:
    Constructor of Parent
    Constructor of Child
    

    Inheritance and Method Overriding: 

    To declare the same method in child class which is already present in the parent class then this is called method overriding. In this case, when we call the method from the child class object, the child class version of the method is called. However, we can call the parent class method using the super keyword as I have shown in the example below:
    class ParentClass{
       //Parent class constructor
       ParentClass(){
        System.out.println("Constructor of Parent");
       }
       void disp(){
        System.out.println("Parent Method");
       }
    }
    class ChildClass extends ParentClass{
       ChildClass(){
        System.out.println("Constructor of Child");
       }
       void disp(){
        System.out.println("Child Method");
            //Calling the disp() method of parent class
        super.disp();
       }
       public static void main(String args[]){
        //Creating the object of child class
        ChildClass obj = new ChildClass();
        obj.disp();
       }
    }
    

    Summary: 

    Inheritance means to inherit the properties from parent. A child can inherit all properties from the parent. A parent can have multiple children. A child can have only one parent. When the method is present in the parent class as well as in child class with the same name and same parameters – Method Overriding. Preference will be given to the overridden method. The super keyword is used to access parent class features.