Automation Testing

TestNG Tutorial | What is Annotations & Framework in…

What is TestNG?

TestNG is an automation testing framework in which NG stands for “Next Generation”. TestNG is inspired by JUnit which uses the annotations (@). TestNG overcomes the disadvantages of JUnit and is designed to make end-to-end testing easy.

Using TestNG, you can generate a proper report, and you can easily come to know how many test cases are passed, failed, and skipped. You can execute the failed test cases separately.

For example:

  • Suppose, you have five test cases, one method is written for each test case (Assume that the program is written using the main method without using testNG). When you run this program first, three methods are executed successfully, and the fourth method is failed. Then correct the errors present in the fourth method, now you want to run only fourth method because first three methods are anyway executed successfully. This is not possible without using TestNG.
  • The TestNG in Selenium provides an option, i.e., testng-failed.xml file in test-output folder. If you want to run only failed test cases means you run this XML file. It will execute only failed test cases.

Beside above concept, you will learn more on TestNG, like what are the Advantages of TestNG, how to create test methods using @test annotations, how to convert these classes into testing suite file and execute through the eclipse as well as from the command line.

Why Use TestNG with Selenium?

Default Selenium tests do not generate a proper format for the test results. Using TestNG in Selenium, we can generate test results.

Most Selenium users use this more than Junit because of its advantages. There are so many features of TestNG, but we will only focus on the most important ones that we can use in Selenium. Following are the key features of Selenium TestNG:

  • Generate the report in a proper format including a number of test cases runs, the number of test cases passed, the number of test cases failed, and the number of test cases skipped.
  • Multiple test cases can be grouped more easily by converting them into testng.xml file. In which you can make priorities which test case should be executed first.
  • The same test case can be executed multiple times without loops just by using keyword called ‘invocation count.’
  • Using testng, you can execute multiple test cases on multiple browsers, i.e., cross browser testing.
  • The TestNG framework can be easily integrated with tools like TestNG Maven, Jenkins, etc.
  • Annotations used in the testing are very easy to understand ex: @BeforeMethod, @AfterMethod, @BeforeTest, @AfterTest
  • WebDriver has no native mechanism for generating reports. TestNG can generate the report in a readable format like the one shown below.
  • TestNG simplifies the way the tests are coded. There is no more need for a static main method in our tests. The sequence of actions is regulated by easy-to-understand annotations that do not require methods to be static.
  • Uncaught exceptions are automatically handled by TestNG without terminating the test prematurely. These exceptions are reported as failed steps in the report.

Advantages of TestNG over JUnit

There are three major advantages of TestNG over JUnit:

  • Annotations are easier to understand
  • Test cases can be grouped more easily
  • Parallel testing is possible

What is Annotation in TestNG?

Annotations in TestNG are lines of code that can control how the method below them will be executed. They are always preceded by the @ symbol. A very early and quick TestNG Example is the one shown below.

TestNG Tutorial

Annotations will be discussed later in the section named “Annotations used in TestNG,”so it is perfectly ok if you do not understand the above TestNG Example just yet. It is just important to note for now that annotations in TestNG are easier to code and understand than in JUnit.

The ability to run tests in parallel is available in TestNG but not in JUnit, so the TestNG framework is more preferred for testers using Selenium Grid.

How to Write Test Cases in TestNG?

Step 1) Write your business logic and insert the TestNG annotations in your code.
Step 2) Add more information like class name, groups name, package name, etc
Step 3) Run the TestNG.

Create Test Case Using TestNG Annotations

Now, we will learn how to create our first test case using TestNG Annotations in Selenium:

Before we create a test case, we should first setup a new TestNG Project in Eclipse and name it as “FirstTestNGProject”.

Setting up a new TestNG Project

Step 1: Click File > New > Java Project

TestNG Tutorial

Step 2: Type “FirstTestNGProject” as the Project Name then click Next.

TestNG Tutorial

Step 3: We will now start to import the TestNG Libraries onto our project. Click on the “Libraries” tab, and then “Add Library…”

TestNG Tutorial

Step 4: On the Add Library dialog, choose “TestNG” and click Next.

TestNG Tutorial

Step 5: Click Finish.

TestNG Tutorial

You should notice that TestNG is included on the Libraries list.

TestNG Tutorial

Step 6: We will now add the JAR files that contain the Selenium API. These files are found in the Java client driver that we downloaded from https://www.selenium.dev/downloads/ when we were installing Selenium and Eclipse in the previous chapters.

TestNG Tutorial

Then, navigate to where you have placed the Selenium JAR files.

TestNG Tutorial

After adding the external JARs, your screen should look like this.

TestNG Tutorial

Step 7: Click Finish and verify that our FirstTestNGProject is visible on Eclipse’s Package Explorer window.

TestNG Tutorial

How to Create a New TestNG Test File

Now that we are done setting up our project in this TestNG tutorial, let us create a new TestNG file.

Step 1: Click on ‘src’ and Choose other.
Right-click on the “src” package folder then choose New > Other…

TestNG Tutorial

Step 2: Select TestNG class.
Click on the TestNG folder and select the “TestNG class” option. Click Next.

TestNG Tutorial

Step 3: Type the values.
Type the values indicated below on the appropriate input boxes and click Finish. Notice that we have named our Java file as “FirstTestNGFile”.

TestNG Tutorial

Step 4: Template Created.
Eclipse should automatically create the template for our TestNG file shown below.

TestNG Tutorial

Coding of our First TestNG Test Case Example

Let us now create our first Test Case that will check if Mercury Tours’ homepage is correct. Type your code as shown in the below TestNG Example:

package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;

public class firsttestngfile {
    public String baseUrl = "http://demo.guru99.com/test/newtours/";
    String driverPath = "C:\\geckodriver.exe";
    public WebDriver driver ; 
     
  @Test
  public void verifyHomepageTitle() {
       
      System.out.println("launching firefox browser"); 
      System.setProperty("webdriver.gecko.driver", driverPath);
      driver = new FirefoxDriver();
      driver.get(baseUrl);
      String expectedTitle = "Welcome: Mercury Tours";
      String actualTitle = driver.getTitle();
      Assert.assertEquals(actualTitle, expectedTitle);
      driver.close();
  }
}

Notice the following.

  • TestNG does not require you to have a main() method.
  • Methods need not be static.
  • We used the @Test annotation. @Test is used to tell that the method under it is a test case. In this case, we have set the verifyHomepageTitle() method to be our test case, so we placed an ‘@Test’ annotation above it.
  • Since we use annotations in TestNG, we needed to import the package org.testng.annotations.*.
  • We used the Assert class. The Assert class is used to conduct verification operations in TestNG. To use it, we need to import the org.testng.Assert package.

You may have multiple test cases (therefore, multiple @Test annotations) in a single TestNG file. This will be tackled in more detail later in the section “Annotations used in TestNG.”

Running the Test

To run the test, simply run the file in Eclipse as you normally do. Eclipse will provide two outputs – one in the Console window and the other on the TestNG Results window.

TestNG Tutorial
TestNG Tutorial

Checking reports created by TestNG

The Console window in Eclipse gives a text-based report of our test case results while the TestNG Results window gives us a graphical one.

TestNG Tutorial

Generating HTML Reports

TestNG has the ability to generate reports in HTML format.

Step 1: After running our FirstTestNGFile that we created in the previous section, right-click the project name (FirstTestNGProject) in the Project Explorer window then click on the “Refresh” option.

TestNG Tutorial

Step 2: Notice that a “test-output” folder was created. Expand it and look for an index.html file. This HTML file is a report of the results of the most recent test run.

TestNG Tutorial

Step 3: Double-click on that index.html file to open it within Eclipse’s built-in web browser. You can refresh this page any time after you rerun your test by simply pressing F5 just like in ordinary web browsers.

TestNG Tutorial

Annotations used in TestNG

In the previous section, you have been introduced to the @Test annotation. Now, we shall be studying more advanced annotations and their usages.

Multiple Test Cases

We can use multiple @Test annotations in a single TestNG file. By default, methods annotated by @Test are executed alphabetically. See the code below. Though the methods c_test, a_test, and b_test are not arranged alphabetically in the code, they will be executed as such.

TestNG Tutorial

Run this code and on the generated index.html page, click “Chronological view.”

TestNG Tutorial

Parameters

If you want the methods to be executed in a different order, use the parameter “priority”. Parameters are keywords that modify the annotation’s function.

  • Parameters require you to assign a value to them. You do.this by placing a “=” next to them, and then followed by the value.
  • Parameters are enclosed in a pair of parentheses which are placed right after the annotation like the code snippet shown below.
TestNG Tutorial

TestNG will execute the @Test annotation with the lowest priority value up to the largest. There is no need for your priority values to be consecutive.

TestNG Tutorial

The TestNG HTML report will confirm that the methods were executed based on the ascending value of priority.

TestNG Tutorial

Multiple Parameters

Aside from “priority,” @Test has another parameter called “alwaysRun” which can only be set to either “true” or “false.” To use two or more parameters in a single annotation, separate them with a comma such as the one shown below.

@Test(priority = 0, alwaysRun = true)
TestNG Tutorial

@BeforeTest and @AfterTest

@BeforeTestmethods under this annotation will be executed prior to the first test case in the TestNG file.
@AfterTestmethods under this annotation will be executed after all test cases in the TestNG file are executed.

Consider the code below.

package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.*;
public class firsttestngfile {
    public String baseUrl = "http://demo.guru99.com/test/newtours/";
    String driverPath = "C:\\geckodriver.exe";
    public WebDriver driver ; 
     
     @BeforeTest
      public void launchBrowser() {
          System.out.println("launching firefox browser"); 
          System.setProperty("webdriver.gecko.driver", driverPath);
          driver = new FirefoxDriver();
          driver.get(baseUrl);
      }
      @Test
      public void verifyHomepageTitle() {
          String expectedTitle = "Welcome: Mercury Tours";
          String actualTitle = driver.getTitle();
          Assert.assertEquals(actualTitle, expectedTitle);
     }
      @AfterTest
      public void terminateBrowser(){
          driver.close();
      }
}

Applying the logic presented by the table and the code above, we can predict that the sequence by which methods will be executed is:

  • 1st – launchBrowser()
  • 2nd – verifyHomepageTitle()
  • 3rd – terminateBrowser()

The placement of the annotation blocks can be interchanged without affecting the chronological order by which they will be executed.

Summary of TestNG Annotations

@BeforeSuite: The annotated method will be run before all tests in this suite have run.

@AfterSuite: The annotated method will be run after all tests in this suite have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the tag have run.

@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.

@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.

@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@BeforeMethod: The annotated method will be run before each test method.

@AfterMethod: The annotated method will be run after each test method.

@Test: The annotated method is a part of a test case

Uncategorized

How to fetch Key and value from My SQL…

A database is a software subsystem that offers an efficient way to store data and request said data via a structured query language known as SQL. Databases store critical business information, thus functioning as the backbone of an entire application. Database testing is a vital part of software testing that involves verifying the accuracy and completeness of data stored in a database.

Automated database testing can cover a wide range of tests, such as data integrity, performance, security, and integration. It can also detect defects or issues in the database, such as data corruption, missing data, incorrect data, and duplicate data.

Naturally, database testing is essential to ensure the system is working correctly. As automation testing with Selenium is most frequently used by QAs, this article will detail how to perform database testing using Selenium.

Java Database Connectivity

JDBC is the standard Java API required for database-independent connectivity between the Java programming language and many databases. This application program interface (API) lets users encode access request statements in a Structured Query Language (SQL). They are then passed to the program that manages the database. It involves opening a connection, creating a SQL Database, executing SQL queries, and arriving at the output.

Steps to create a JDBC Application

To create a JDBC application, follow the steps below:

  1. Import the packages: Include the packages that contain the JDBC classes required for database programming.
  2. Register the JDBC driver: Initialize a driver to open a communication channel with the database. Register to the database with the command:
    Class.forName(“com.mysql.jdbc.Driver”); // class.forName load the Driver class
  3. Open a connection: After the driver registration, use the getConnection() method to create a Connection object, representing a physical connection with the database.
  4. Execute a query: Use an object of type ‘Statement’ to build and submit a SQL statement to the database.
  5. Extract data from the result set: Use the appropriate getXXX() method.
  6. Clean up the environment: Close all database resources that rely on JVM garbage collection.

2. Selenium Database Connection

Selenium is one of the prominent automation testing tools. As mentioned before, Selenium performs only UI validations. Thus, this article will depict a JDBC connection as Selenium doesn’t support database testing directly, but it can be done with connectors like JDBC and ODBC. This article uses JDBC to connect to a database, and test cases are verified using TestNG framework.

3. Database testing using Selenium

Step 1: Create a database in command prompt and insert the tables.
Step 2: Establish a connection to the database using JDBC.
Step 3: Execute the MySQL queries and process records present in the database.
Step 4: Integrate TestNG with JDBC to perform Database Testing.

Have a look at the script below:

package com.test.traveltest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SeleniumDatabaseTesting {
// Connection object
static Connection con = null;
// Statement object
private static Statement stmt;
// Constant for Database URL
public static String DB_URL = "jdbc:mysql://127.0.0.1:3306/hrmdb";
//Database Username
public static String DB_USER = "root";
// Database Password
public static String DB_PASSWORD = "rahul";

public static WebDriver driver;
public static String uname;
public static String uval;
public static String pwd;
public static String pval;
public static String loginbtn;

@BeforeTest
public void setUp() throws Exception {
	
	System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\src\\main\\java\\drivers\\chromedriver1.exe");
  	driver = new ChromeDriver();
	driver.manage().window().maximize();
	driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
try{
// Database connection
String dbClass = "com.mysql.cj.jdbc.Driver";
Class.forName(dbClass).newInstance();
// Get connection to DB
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// Statement object to send the SQL statement to the Database
stmt = con.createStatement();
}
catch (Exception e)
{
e.printStackTrace();
}
}

@Test (priority = 0)
public void testuname() {
try{
String query = "select * from login where id = '" +1+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
uname = res.getString(2);
uval = res.getString(3);
}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.name(uname)).sendKeys(uval);

}

@Test (priority = 1)
public void testpwd() {
try{
String query = "select * from login where id = '" +2+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
pwd = res.getString(2);
pval = res.getString(3);
}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.name(pwd)).sendKeys(pval);

}

@Test (priority = 2)
public void testlogin() {
try{
String query = "select * from login where id = '" +3+"'";
// Get the contents of userinfo table from DB
ResultSet res = stmt.executeQuery(query);
// Print the result untill all the records are printed
// res.next() returns true if there is any next record else returns false
while (res.next())
{
System.out.print(res.getString(1));
System.out.print(" | " + res.getString(2));
System.out.print(" | " + res.getString(3));
System.out.println();
loginbtn = res.getString(2);

}
}
catch(Exception e)
{
e.printStackTrace();
}

driver.findElement(By.xpath(loginbtn)).click();

}

@AfterTest
public void tearDown() throws Exception {
// Close DB connection
if (con != null) {
con.close();
}
}
}
Automation Testing

How can we submit a form without click method?

The click() and submit() functions are quite similar in terms of functionalities. However there are minor differences. Let us discuss some differences between them.

The submit() function is applicable only for <form> and makes handling of form easier. It can be used with any element inside a form. The click() is only applicable to buttons with type submit in a form.

The submit() function shall wait for the page to load however the click() waits only if any explicit wait condition is provided. If a form has a submit of type button, the submit() method cannot be used. Also, if a button is outside <form>, then submit() will not work.

Thus we see that click() works for both type buttons irrespective of the fact that the button is inside or outside of <form>. Let us take up the below form for implementation.

package com.test.traveltest;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SubmitForm {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\main\\java\\drivers\\chromedriver.exe");
		WebDriver driver = new ChromeDriver();
	      String url = "https://www.facebook.com/";
	      driver.get(url);
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      // identify elements
	      driver.findElement(By.id("email")).sendKeys("abc@gmail.com");
	      driver.findElement(By.id("pass")).sendKeys("123456");
	      // submitting form with submit()
	      driver.findElement(By.id("pass")).submit();
	      driver.quit();

	}