DataProvider in TestNG using Excel

HOME

In the previous tutorial, I have explained the DataProvider in TestNG without using Excel. In this tutorial, I will explain the use of Excel in DataProvider for TestNG.

I have created an excel – SearchInBing.xlsx and placed on Desktop. You can create a TestData folder in your project and place the excel file within it. So, my datasheet looks like below-

Next, we will create a DataProvider method that will use another method to read the excel file & create a 2D object from the row & column values of the excel and return the same value, so that our test script can use it. The code for it would look like below-

@DataProvider(name = "excelData")
	public Object[][] excelDataProvider() throws IOException {
		// We are creating an object from the excel sheet data by calling a method that
		// reads data from the excel stored locally in our system
		Object[][] arrObj = getExcelData(
				"C:\\Users\\Vibha\\Desktop\\SearchInBing.xlsx",
				"Details");
		return arrObj;
	}

	// This method handles the excel - opens it and reads the data from the
	// respective cells using a for-loop & returns it in the form of a string array
	public String[][] getExcelData(String fileName, String sheetName) throws IOException {
		String[][] data = null;
		try {
			
			FileInputStream fis = new FileInputStream(fileName);
			XSSFWorkbook workbook = new XSSFWorkbook(fis);
			XSSFSheet sheet = workbook.getSheet(sheetName);
			XSSFRow row = sheet.getRow(0);
			int noOfRows = sheet.getPhysicalNumberOfRows();
			int noOfCols = row.getLastCellNum();
			Cell cell;
			data = new String[noOfRows - 1][noOfCols];

			for (int i = 1; i < noOfRows; i++) {
				for (int j = 0; j < noOfCols; j++) {
					row = sheet.getRow(i);
					cell = row.getCell(j);
					data[i - 1][j] = cell.getStringCellValue();
				}
			}
		} catch (Exception e) {
			System.out.println("The exception is: " + e.getMessage());
		}
		return data;
	}

Now, create a class which contains the test code. By default, the data provider will be looked for in the current test class or one of its base classes. If you want to put your data provider in a different class, it needs to be a static method or a class with a non-arg constructor, and you specify the class where it can be found in the dataProviderClass attribute.

public class DataProviderWithExcelDemo {

	WebDriver driver;

	@BeforeMethod
	public void setUp() {
		System.out.println("Start test");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Software\\chromedriver_win32_93.0.4577.15\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://www.bing.com");
		driver.manage().window().maximize();

	}

	@Test(dataProvider = "excelData", dataProviderClass = ExcelDataProvider.class)
	public void search(String keyWord1, String keyWord2) {

		WebElement txtBox = driver.findElement(By.id("sb_form_q"));
		txtBox.sendKeys(keyWord1, " ", keyWord2);
		System.out.println("Keyword entered is : " + keyWord1 + " " + keyWord2);
		txtBox.sendKeys(Keys.ENTER);
		System.out.println("Search results are displayed.");
	}

	@AfterMethod
	public void burnDown() {
		driver.quit();
	}

}

To run the code, right click and Select – TestNG Test.

The Execution status will look like as shown below

This test execution generate reports under test-output folder.

We are concerned about two reports – index.html and emailable-report.html.

Below is the image of emailable-report.html.

Below is the image of index.html.

See how easy it is to read data from excel and use in the Test Code using DataProvider.

I hope you have enjoyed this tutorial. Happy Learning!!

DataProviders in TestNG

HOME

In the last tutorial, I have explain the Parameters in TestNG which passes different test data to the test case as arguments. Similar to TestNG Parameters, DataProviders are a means to pass data to test scripts in TestNG. In this tutorial, I will explain about the DataProviders in TestNG.

What is DataProvider in TestNG?

The DataProvider in TestNG is another way to pass the parameters in the test function, the other one being TestNG parameters. Using DataProvider in TestNG, we can easily inject multiple values into the same test case. It comes inbuilt in TestNG and is popularly used in data-driven frameworks.

Syntax of DataProvider

@DataProvider (name = "name_of_dataprovider")
public Object[][] dpMethod() {
    return new Object [][] { values}
}
  •  A Data Provider is a method on the class that returns an array of array of objects.  This method is annotated with @DataProvider
  • A @Test method specifies its Data Provider with the dataProvider attribute. This name must correspond to a method on the same class annotated with @DataProvider(name=”…”) with a matching name.
  • TestNG dataprovider returns a 2d list of objects..An array of array of objects (Object[][]) where the first dimension’s size is the number of times the test method will be invoked and the second dimension size contains an array of objects that must be compatible with the parameter types of the test method.
  • DataProviders are not declared on top of the functions like TestNG parameters but have a method of their own, which in regular speaking terms called a dataprovider method. For example, dpMethod here.
  • The dataprovider name calls the dataprovider method, and if there is no name specified by the tester, then the dataprovider method is the default name used in the receiving @Test case.
  • Data providers can run in parallel with the attribute parallel.

Below is the basic example of using DataProvider in TestNG.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class DataProviderDemo {

	WebDriver driver;

	@DataProvider(name = "testData")
	public Object[][] dataProvFunc() {
		return new Object[][] { { "Selenium" }, { "TestNG" } };
	}

	@BeforeMethod
	public void setUp() {

		System.out.println("Start the test");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Software\\chromedriver\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://www.bing.com/");
		driver.manage().window().maximize();

	}

	// Passing the dataProvider to the test method through @Test annotation
	@Test(dataProvider = "testData")
	public void search(String keyWord) {
		WebElement txtBox = driver.findElement(By.id("sb_form_q"));
		txtBox.sendKeys(keyWord);
		System.out.println("Keyword entered is : " + keyWord);
		txtBox.sendKeys(Keys.ENTER);
		System.out.println("Search result is displayed.");
	}

	@AfterMethod
	public void burnDown() {
		driver.quit();

		System.out.println("End the test");
	}

}

In the above example, I am passing two search keywords, viz “Selenium” and “TestNG” to the test method using the DataProvider method. You can run the code and check the output. It will be as shown below-

Here, Test is executed with two values, but we have run the test only once.

Inheriting DataProvider in TestNG

It is messy to have supporting methods like DataProvider and test code in one class. It is always preferred to declare the test case in one class and define TestNG parameters like DataProviders in another class. By default, the data provider will be looked for in the current test class or one of its base classes. If you want to put your data provider in a different class, it needs to be a static method or a class with a non-arg constructor, and you specify the class where it can be found in the dataProviderClass attribute.

Let us create separate classes for the DataProvider method and the test method, as shown below:

DataProvider Class

public class DPDemo {

	@DataProvider(name = "testData")
	public Object[][] dataProvFunc() {
		return new Object[][] { 
          { "Selenium" }, { "TestNG" }, { "Automation" } };
	}
}

We can see that all we did was create a DataProvider method in a Class and create a new class for Test Code.

public class DataProviderInheritanceDemo {

	WebDriver driver;

	@BeforeMethod
	public void setUp() {

		System.out.println("Start the test");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Software\\chromedriver\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://www.bing.com/");
		driver.manage().window().maximize();

	}

	// Passing the dataProvider to the test method through @Test annotation
	@Test(dataProvider = "testData", dataProviderClass = DPDemo.class)
	public void search(String keyWord) {
		WebElement txtBox = driver.findElement(By.id("sb_form_q"));
		txtBox.sendKeys(keyWord);
		System.out.println("Keyword entered is : " + keyWord);
		txtBox.sendKeys(Keys.ENTER);
		System.out.println("Search result is displayed.");
	}

	@AfterMethod
	public void burnDown() {
		driver.quit();

		System.out.println("End the test");
	}

}

As you can see, to handle the inheritance, all we did was add an attribute to the test method (highlighted above), which specifies the class that has the DataProvider method. 

Passing Multiple Parameter Values in TestNG DataProviders

Passing multiple values is pretty similar to passing numerous parameters. The only difference is that we will pass various values to a single parameter so that a string of input(s) is sent in one go.

Let us quickly understand this concept with the help of the code as shown below.

DataProvider Class

public class DPDemo {

	@DataProvider(name = "testData")
	public Object[][] dataProvFunc() {
		return new Object[][] { { "Automation Tester", "2-5 years" }, { "Performance Tester", "3+ years" },
				{ "DevOps", "5+ years" } };
	}
}

Test Code – DataProviderInheritanceDemo

public class DataProviderInheritanceDemo {

	WebDriver driver;

	@BeforeMethod
	public void setUp() {

		System.out.println("Start the test");
		System.setProperty("webdriver.chrome.driver",
				"C:\\Users\\Vibha\\Software\\chromedriver\\chromedriver.exe");
		driver = new ChromeDriver();
		driver.get("https://www.bing.com/");
		driver.manage().window().maximize();

	}

	// Passing the dataProvider to the test method through @Test annotation
	@Test(dataProvider = "testData", dataProviderClass = DPDemo.class)
	public void search(String keyWord1, String keyWord2) {

		WebElement txtBox = driver.findElement(By.id("sb_form_q"));
		txtBox.sendKeys(keyWord1, keyWord2);
		System.out.println("Keyword entered is : " + keyWord1 + " " + keyWord2);
		txtBox.sendKeys(Keys.ENTER);
		System.out.println("Search result is displayed.");
	}

	@AfterMethod
	public void burnDown() {
		driver.quit();

		System.out.println("End the test");
	}
}

Run the test script, and you will see both the values for the TestNG parameters being passed in one go, the output for it would be as follows-

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

How to create and run TestNG.xml of a TestNG class

HOME

There are 2 ways to run TestNG tests – using Run As TestNG tests and from testng.xml.

In this tutorial, I’m explaining how to create and run tests using TestNG.xml.

Step 1 – In the below project, there is no testng.xml present.

Step 2 – Right click on class name “API_Test.java” and navigate “TestNG–>Convert to TestNG“.

Step 3 – Now a new window for testng.xml will be generated as shown below. Click the Finish Button.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test thread-count="5" name="Test">
    <classes>
      <class name="com.example.RestAssured_TestNG_Demo.API_Test"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Step 4 – A xml file named “testng.xml” will be generated in project hierarchy.

Step 5 – Right click on this testng.xml and select Run As–> Testng Suite

Step 6 – You will view the result in two different tabs: Console and “Results of running suite”. Below is the image of Rest of running suite tab.

Multiple Classes

Let us imagine a sceanrio where there are 3 classes and we want to run them all together, you can done that by creating a testng.xm and mention all 3 classes in that testng.xml.

Select all 3 classes and right click and navigate “TestNG–>Convert to TestNG

This is how the testng.xml will look like for multiple classes.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test thread-count="5" name="Test">
    <classes>
      <class name="com.example.RestAssured_TestNG_Demo.API_Test1"/>
      <class name="com.example.RestAssured_TestNG_Demo.Test3"/>
      <class name="com.example.RestAssured_TestNG_Demo.Test2"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Right click on this testng.xml and select Run As–> Testng Suite.  You will get the result in two tabs: Console and “Results of running suite”. Rhis shows that all the tests present withing the three classes are executed.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Hard Assert and Soft Assert in TestNG

 HOME

In this tutorial, will discuss about Hard Assert and Soft Assert in TestNG. Before starting with Hard and Soft Assert, go through What is Assert in TestNG.

What is Hard Assert?

Hard Assertion throws AssertionError immediately when an Assert Condition fails and moves to next @Test method

Suppose, there are 2 assertions in a Test and the first assertion fails, then HardAssertion do not execute the second Assertion Condition and declare the test as failed

As you can see in the below example, there are 2 assert conditions under Test – AssertionFailure(). As first Assert Condition fails, it moved directly to second test without executing another Assert Condition

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
 
public class HardAssertionDemo {

     @Test
     public void AssertionFailure() {
           System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           WebDriver driver = new FirefoxDriver();
 
           driver.get("https://duckduckgo.com/");
           String actualTitle = "DuckDuckGo — Privacy, simplified";
 
           String expectedTitle = driver.getTitle();
           String expectedText = driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[1]")).getText();
 
           /* Hard Assert */
           Assert.assertEquals(expectedTitle, actualTitle, "Incorrect page title");
           Assert.assertEquals("Privacy Protection For Any Device", expectedText);
     }
 
     @Test
     public void print() {
           System.out.println("Hard Assertion is displayed");
     }
}

What is Soft Assert?

To overcome above mentioned problem, there is another type of assertion called Soft Assert

Soft Assert does not throw an exception when an Assert Condition fails and continue with the next step after the Assert Condition.

Soft assert does not include by default in TestNG. For this, you need to include the package org.testng.asserts.SoftAssert;

SoftAssert softAssertion = new SoftAssert();

 Create an object of SoftAssertion to run Assert Conditions

Below is an example of Soft Assert

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
 
public class SoftAssertionDemo {

     @Test
     public void AssertionFailure() {
           SoftAssert softAssertion = new SoftAssert();
 
           System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           WebDriver driver = new FirefoxDriver();
 
           driver.get("https://duckduckgo.com/");
 
           String actualTitle = "DuckDuckGo — Privacy, simplified";
 
           String expectedTitle = driver.getTitle();
           String expectedText1 = driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[1]")).getText();
 
           /* Soft Assert */
           softAssertion.assertEquals(expectedTitle, actualTitle, "Incorrect page title");
           softAssertion.assertEquals("Privacy Protection For Any Device", expectedText1);
     }
 
     @Test
     public void print() {
           System.out.println("Soft Assertion is displayed");
     } 
 
}

AssertAll

If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is. 

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
 
public class SoftAssertionDemo {
 
     @Test
     public void AssertionFailure() {
           SoftAssert softAssertion = new SoftAssert();
 
           System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
           WebDriver driver = new FirefoxDriver();
           driver.get("https://duckduckgo.com/");
 
           String actualTitle = "DuckDuckGo — Privacy, simplified";
           String expectedTitle = driver.getTitle();
           String expectedText1 = driver.findElement(By.xpath("/html/body/div/div[2]/div/div[3]/div[1]")).getText();
 
           /* Soft Assert */
           softAssertion.assertEquals(expectedTitle, actualTitle, "Incorrect page title");
           softAssertion.assertEquals("Privacy Protection For Any Device", expectedText1);
 
           softAssertion.assertAll();
     }
 
     @Test
     public void print() {
           System.out.println("Soft Assertion is displayed");
     } 
}

TestNG Listeners in Selenium

 HOME

Listener is defined as interface that modifies the default TestNG’s behavior. There are several interfaces that allow you to modify TestNG‘s behavior that are called “TestNG Listeners”.  It allows customizing TestNG reports or logs. There are many types of TestNG  listeners available. Here are a few listeners:

  • IAnnotationTransformer 
  • IAnnotationTransformer2 
  • IHookable 
  • IInvokedMethodListener 
  • IMethodInterceptor 
  • IReporter 
  • ISuiteListener 
  • ITestListener 

When you implement one of these interfaces, you can let TestNG know about it with either of the following ways:

  • Using in your testng.xml file.
  • Using the @Listeners annotation on any of your test classes.

ITestListener has following methods

  • OnStart  Invoked before running all the test methods belonging to the classes inside the tag and calling all their Configuration methods.
  • onTestSuccess onTestSuccess method is called on the success of any Test.
  • onTestFailure onTestFailure method is called on the failure of any Test.
  • onTestSkipped– onTestSkipped method is called on skipped of any Test.
  • onTestFailedButWithinSuccessPercentage– method is called each time Test fails but is within success percentage. Invoked each time a method fails but has been annotated with successPercentage and this failure still keeps it within the success percentage requested.
  • onFinish– Invoked after all the test methods belonging to the classes inside the tag have run and all their Configuration methods have been called.
  • onTestStart Invoked each time before a test will be invoked. The ITestResult is only partially filled with the references to class, method, start millis and status.

Here, I explain the use of listener – ITestListener  in a program mentioned below

Step 1) Create class “ListenerDemo” that implements ‘ITestListener’. Add methods like onTestFailure, onTestSkipped, onTestStart, onTestSuccess to this class

Step 2) Create another class “ListenerTestCases” for the login process automation. Selenium will execute this ‘TestCases’ to login automatically.

Step 3) Next, implement this listener in our regular project class i.e. ” ListenerTestCases “. There are two different ways to connect to the class and interface.

The first way is to use Listeners annotation (@Listeners) as shown below:

@Listeners(com.selenium.testng.TestNGDemo.ListenerDemo.class)

Step 4): Execute the “ListenerTestCases” class. Methods in class “TestPass ” are called automatically according to the behavior of methods annotated as @Test.

Step 5): Verify the Output that logs displays at the console.

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
 
public class ListenerDemo implements ITestListener {
 
            // When Test case get failed, this method is called.
            public void onTestFailure(ITestResult Result) {
                        System.out.println("The name of the testcase failed is :" + Result.getName());
            }
 
            // When Test case get Skipped, this method is called.
            public void onTestSkipped(ITestResult Result) {
                        System.out.println("The name of the testcase Skipped is :" + Result.getName());
            }
 
            // When Test case get Started, this method is called.
            public void onTestStart(ITestResult Result) {
                        System.out.println(Result.getName() + " test case started");
            }
 
            // When Test case get passed, this method is called.
            public void onTestSuccess(ITestResult Result) {
                        System.out.println("The name of the testcase passed is :" + Result.getName());
            } 
}

In the below test, there are 2 test cases. One Test is passes and another fails. When we are executing ListenerTestCases, it will call the ListenersDemo internally.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
importorg.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
 
@Listeners(com.selenium.testng.TestNGDemo.ListenerDemo.class)
public class ListenerTestCases {
 
            static WebDriver driver;
 
            @Test
            public void TestPass() {
                        System.setProperty("webdriver.chrome.driver",
                                    "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
                        driver= new ChromeDriver();
                        driver.get("https://opensource-demo.orangehrmlive.com/");
                        driver.findElement(By.name("txtUsername")).sendKeys("Admin");
                        driver.findElement(By.name("txtPassword")).sendKeys("admin123");
                        driver.findElement(By.id("btnLogin")).submit();
                        String dashboardTitle = driver.findElement(By.id("welcome")).getText();
                        Assert.assertTrue(dashboardTitle.contains("Welcome"));
            }
 
            @Test
            public void TestFail() {
                        System.setProperty("webdriver.chrome.driver",
                                    "C:\\Users\\SingVi04\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
                        driver= new ChromeDriver();
                        driver.get("https://opensource-demo.orangehrmlive.com/");
                        driver.findElement(By.name("txtUsername")).sendKeys("Admin");
                        driver.findElement(By.name("txtPassword")).sendKeys("admin123");
                        driver.findElement(By.id("btnLogin")).submit();
                        String dashboardTitle = driver.findElement(By.id("welcome")).getText();
                        Assert.assertTrue(dashboardTitle.contains("Hello"));
            }
}

Output
TestFail test case started
The name of the testcase failed is :TestFail
TestPass test case started
The name of the testcase passed is :TestPass
PASSED: TestPass
FAILED: TestFail
java.lang.AssertionError: did not expect to find [true] but found [false]

To execute this program, we need to Right click and select Run as – TestNG

There is another way to execute the Listener class which is using testng.xml. There is a Listener class named “ListenerDemowhere the implementation of various methods of listener is present. If we want to run thes tests using testng.xml, then there is no need of mentioning Listeners in the ListenerTestCases class.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "TestSuite">
<listeners>
<listener class-name ="com.selenium.testng.TestNGDemo.ListenerDemo"/>
</listeners>
 
<test name ="Test">
<classes>
<class name="com.selenium.testng.TestNGDemo.ListenerTestCases"/>
</classes>
</test>
</suite>

The test execution result will look like something shown below

TestNG generates various type of reports under test-output folder. Open “emailable-report.html”, as this is a html report open it with browser. It will look like something below.

TestNG also produce “index.html” report and it resides under test-output folder

There is another example of Listener –ITestResult

How to pass Parameters in TestNG

 HOME

One of the important features of TestNG is ability to pass different test data to a test case as arguments that is called parametrization

There are mainly two ways through which we can provide parameter values to TestNG tests.

  1. Through testng.xml XML configuration file
  2.   Through DataProviders

In this tutorial, we will discuss about using testng.xml for parameterization. If we need to pass some simple values such as String or Integer types to the test methods at runtime, there is a something called @Parameter where parameter values through TestNG XML configuration files pass to test.

@Parameters("value")

Lets explain how we can use parameters

Step 1 – Create a java test class, say, TestNGParameterizationDemo.java

Step 2 – Add test method parameterizedTest() to the test class. This method takes a string as input parameter

Add the annotation @Parameters(“browser”) to this method. The parameter pass a value from testng.xml

Step 3 – Create a TestNG.xml and pass the value of parameter in  this configuration file.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
 
public class TestNGParameterizationDemo {
            WebDriver driver;

            @Test
            @Parameters("browser")
            public void parameterizedTest(String browser) {
                        if (browser.equalsIgnoreCase("firefox")) {
 
                                    // set path to geckodriver.exe and create gecko instance
                                    System.setProperty("webdriver.gecko.driver",
                                                            "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\geckodriver-v0.27.0-win64\\geckodriver.exe");
                                    driver = new FirefoxDriver();
                                    System.out.println("Browser Started:" + browser);
                        }
 
                        // Check if parameter passed as 'chrome'
                        else if (browser.equalsIgnoreCase("chrome")) {
 
                                    // set path to chromedriver.exe and create chrome instance
                                    System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
                                    driver = new ChromeDriver();
                                    System.out.println("Browser Started:" + browser);
                        }
            }
}

Output
Browser Started:Chrome

TestNG.xml looks like as shown below. Here, parameter name is browser name value for browser is “Chrome”. So, this “Chrome” value is pass to Test as parameter and as a result a Google Chrome browser opens.

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "TestSuite">
  <test name="ChromeTest">
<parameter name="browser"value="Chrome" />
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGParameterizationDemo">
</class>
</classes>
</test>
</suite>

Cross Browser Testing using Selenium

 HOME

What is Cross Browser Testing?

Cross Browser is a technique in which a web application tests on different browsers and operating systems.  Cross Browser testing, make sure that the site rendered the same in every browser.

Suppose, we have to execute 25 tests cases to test a web application on Google Chrome Browser and it takes around 4 hrs to execute these tests. However, we do not know if a user is going to access the web application on which browser. Therefore, now the same set of test cases need to executes on Firefox, Edge, Internet Explorer, Safari and Opera.

Therefore, now we need to execute 25*6=150 test cases and test execution hour changes from 4 to 24 hrs to check that the web application is working as expected. What is the best approach to handle this situation is to automate these tests and perform cross browser testing

Why do we need to perform cross browser testing?

Each website is built by anyone or combination of these technologies – HTML, CSS and Javascript. Each browser uses different rendering engines to compute these technologies. Chrome uses Blink, WebKit on iOS, V8 JavaScript engine, Firefox uses Gecko, Edge usesChromium-based with Blink and V8 engines, Safari uses Webkit rendering engine, IE uses Trident and so on.

1) Font size, image orientation and alignment mismatch in different browsers

2) Different browser is compatible with different operating systems

3) CSS,HTML validation difference can be there

Lets see an example of Cross Browser testing using TestNG

Step 1 – We have used Selenium Webdriver with TestNG to automate the test cases to run on browsers – Chrome, Firefox and Edge

Step 2 – The test are running on all 3 browsers in parallel as we have used  parallel=“tests”

Step 3 – thread-count=”3″ means that 3 threads will start and each browser will use a thread

Step 4 –   @Parameters(“browser”) – parameter will be passed from testng.xml

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import junit.framework.Assert;
 
public class TestNGCrossBrowserDemo {
      WebDriver driver;
 
       @BeforeClass
       @Parameters("browser")
       public void setup(String browser) throws Exception {
 
          // Check if parameter passed from TestNG is 'firefox'
          if (browser.equalsIgnoreCase("firefox")) {
 
                // set path to geckodriver.exe and create gecko instance
                 System.setProperty("webdriver.gecko.driver",
                                                            "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\geckodriver-v0.27.0-win64\\geckodriver.exe");
                 driver = new FirefoxDriver();
                 System.out.println("Browser Started:" + browser);
          }
 
          // Check if parameter passed as 'chrome'
           else if (browser.equalsIgnoreCase("chrome")) {
 
                // set path to chromedriver.exe and create chromeinstance
                  System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
                   driver = new ChromeDriver();
                   System.out.println("Browser Started:" + browser);
          }
 
          // Check if parameter passed as 'edge'
           else if (browser.equalsIgnoreCase("Edge")) {
 
               // set path to chromedriver.exe and create edge instance
                System.setProperty("webdriver.edge.driver",
                                                      "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\edgedriver_win64\\msedgedriver.exe");
               driver = new EdgeDriver();
                System.out.println("Browser Started:" + browser);
           }
 
           else {
                  // If no browser passed throw exception
                    throw new Exception("Browser is not correct");
           }
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
       }
 
        @Test
        public void testTitle() throws InterruptedException {
                        driver.get("https://configureselenium.blogspot.com/2019/10/testng-what-is-testng.html");
              String actualTitle = driver.getTitle();
              System.out.println("Title- " + actualTitle);
 
              System.out.println("Test Case One with Thread Id:- " + Thread.currentThread().getId());
               Assert.assertEquals("TestNG Framework - Introduction to TestNG", actualTitle);
            }
 
      @AfterClass
      public void afterTest() {

       // close the browser
       driver.quit();
    }
}

Output

Browser Started:Edge
Browser Started:Chrome
Title- TestNG Framework - Introduction to TestNG
Test Case One with Thread Id:- 15
Title- TestNG Framework - Introduction to TestNG
Test Case One with Thread Id:- 13Browser Started:Firefox
Title- TestNG Framework - Introduction to TestNG
Test Case One with Thread Id:- 14

We need to specify the values of browser in the TestNG XML file that will pass to the test case file.

<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite"thread-count="3" parallel="tests">
<test name="ChromeTest">
<parameter name="browser"value="Chrome" />
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGCrossBrowserDemo">
</class>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser"value="Firefox" />
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGCrossBrowserDemo">
</class>
</classes>
</test>
<test name="EdgeTest">
<parameter name="browser"value="Edge" /> 
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGCrossBrowserDemo">
</class>
</classes>
</test>
</suite>

To execute this program, we need to Right click on the program and select Run as – TestNG Test

The test execution result looks like as shown below. It shows the test execution status of all the tests. As, in this program, 3 tests are executed and all 3 of them passes. The same result can be depicted from below image

TestNG generates various type of reports under test-output folder like emailable-report.html, index.html, testng-results.xml

We are interested in ’emailable-report.html’ report. Open ’emailable-report.html’, as this is a html report open it with browser. Below image shows emailable-report.html.

TestNG also produce “index.html” report and it resides under test-output folder. Below image shows index.html report.

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

Assertions in TestNG

HOME

What is Assertion?
 

Assertions in TestNG are a way to verify that the expected result and the actual result matches or not in the test case.  A test is considered successful ONLY if it is completed without throwing any exception. An example of assertion can be logging into the website, checking the title of the webpage, verifying the functionality of an input box that takes only integers, etc.

Below are few commonly used assertions in TestNG.

1. Assert.assertEquals(String actual, String expected) – It takes two string arguments and checks whether both strings are equal or not. If they are not, it will fail the test and an AssertionError is thrown.

2. Assert.assertEquals(String actual, String expected, String message) – It takes two string arguments and checks whether both strings are equal or not. If they are not, it will fail the test and an AssertionError is thrown with message provided as argument.

3. Assert.assertEquals(boolean actual, boolean expected) – It takes two Boolean arguments and checks whether both are equal or not. If they are not, it will fail the test and an AssertionError is thrown.

4. Assert.assertEquals(java.util.Collection actual, java.util.Collection expected, java.lang.String message) – It takes two collection objects and verifies both collections contain the same elements and with the same order. If they are not, it will fail the test and an AssertionError is thrown.

5. Assert.assertTrue(condition) – It takes one boolean argument and checks that a condition is true or not. If not, it will fail the test and an AssertionError is thrown.

6. Assert.assertTrue(condition, message) – It takes one boolean argument and checks that a condition is true or not. If not, it will fail the test and an AssertionError is thrown with message provided as argument.

7. Assert.assertFalse(condition) – It takes one boolean argument and checks that a condition is false or not. If not, it will fail the test and an AssertionError is thrown.

8. Assert.assertFalse(condition, message) – It takes one boolean argument and checks that a condition is false or not. If not, it will fail the test and an AssertionError is thrown with message provided as argument.

9. Assert.assertSame(String actual, String expected) – It asserts that two objects refer to the same object. If they do not, an AssertionError is thrown.

10. Assert.assertNotSame(String actual, String expected) – It asserts that two objects do not refer to the same object. If they do, an AssertionError is thrown.

 
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNGAssertionDemo {
            
            @Test
            public void testAssertions() {
                        // test data
                        String str1 = new String("TestNG");
                        String str2 = new String("TestNG");
                        String str3 = null;
                        String str4 = "TestNG";
                        String str5 = "TestNG";
                        String str6 = new String("Not_TestNG");
 
                        int val1 = 5;
                        int val2 = 6;
 
                        // Check that two objects are equal
                        Assert.assertEquals(str1, str2);
                        System.out.println("Equals Assertion is successful");
 
                      // Check that two objects are not equal
                        Assert.assertNotEquals(str1, str6);
                        System.out.println("NotEquals Assertion is successful");
 
                        // Check that a condition is true
                        Assert.assertTrue(val1 < val2);
                        System.out.println("True Assertion is successful");
 
                        // Check that a condition is false
                        Assert.assertFalse(val1 > val2);
                        System.out.println("False Assertion is successful");
 
                        // Check that an object isn't null
                        Assert.assertNotNull(str1);
                        System.out.println("Not Null Assertion is successful");
 
                        // Check that an object is null
                        Assert.assertNull(str3);
 
                        // Check if two object references point to the same object
                        Assert.assertSame(str4, str5);
                        System.out.println("Same Assertion is successful");
 
                        // Check if two object references not point to the same object
                        Assert.assertNotSame(str1, str3);
                        System.out.println("Not Same Assertion is successful");
            }
}

Output
Equals Assertion is successful 
NotEquals Assertion is successful 
True Assertion is successful 
False Assertion is successful 
Not Null Assertion is successful 
Same Assertion is successful 
Not Same Assertion is successful 

Lets see if an assertion fails, how the output looks shown below. In the below example, we are verifying the pageTitle of Gmail. If the test fails, we should see the message provided in the assertion also.

import org.openqa.selenium.WebDriver;
importorg.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
 
public class TestNGAssertionFailureDemo {
            @Test
            public void AssertionFailure() throws InterruptedException {
                        System.setProperty("webdriver.gecko.driver", "src\\test\\resources\\webdrivers\\window\\geckodriver.exe");
 
                        WebDriver driver = new FirefoxDriver();
                        // Test Condition 1: If Page title matches with actualTitle then it finds email
                        // title and enters the value which we pass
                        driver.get("https://www.gmail.com");
                        String actualTitle = "Google";
                        String expectedTitle = driver.getTitle();
                        Assert.assertEquals(expectedTitle, actualTitle, "Incorrect page title");
            }
}

Output
FAILED: AssertionFailure
java.lang.AssertionError: Incorrect page title expected [Google] but found [Gmail]

You can show in the output console, there is an error message “Incorrect page title” as we have mentioned this message in the Assertion.

TestNG Annotations

 HOME

In the previous tutorial, we have discussed How to Download and Install TestNG in Eclipse. In the this tutorial, we are going to discuss about the various annotations available in TestNG. Below is the list of annotations:-

  • @Test – This marks a class or a method as a part of the test.
  • @BeforeSuite – The @BeforeSuite method in TestNG runs before the execution of all other test methods. It will run only once before all tests in the suite have to run
  • @AfterSuite – The @AfterSuite method in TestNG runs after the execution of all other test methods. It will run only once after all tests in the suite have run
  • @BeforeTest – The @BeforeTest method in TestNG runs before the execution of first @Test method. It runs only once per class.
  • @AfterTest – The @AfterTest method in TestNG executes after the execution of all the test methods that are inside that folder.
  • @BeforeClass – The @BeforeClass method in TestNG will run before the first method invokes of the current class.
  • @AfterClass – The @AfterClass method in TestNG will execute after all the test methods of the current class execute.
  • @BeforeMethod – The @BeforeMethod method in TestNG will execute before each test method. 
  • @AfterMethod – The @AfterMethod method in TestNG will run after each test method is executed.
  • @BeforeGroups – The @BeforeGroups method in TestNG run before the test cases of that group execute. It executes just once.
  • @AfterGroups – The @AfterGroups method in TestNG run after the test cases of that group execute. It executes only once. 
  • @Parameters –This annotation is used to pass parameters to test methods.
  • @DataProvider – If we use @DataProvider annotation for any method that means you are using that method as a data supplier. The configuration of @DataProvider annotated method must be like it always return Object[][] which we can use in @Test annotated method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
  • @Factory – Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].
  • @Listeners – This annotation is used with test class. It helps in writing logs and results.

Lets see a program to understand the sequence in which these annotations run in the program

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 TestNGAnnotationDemo {
    
    // Test Case 1
     @Test
     public void testCase1() {
           System.out.println("This is Test Case 1");
     }
 
     // Test Case 2
     @Test
     public void testCase2() {
           System.out.println("This is Test Case 2");
     }
 
     @BeforeMethod
     public void beforeMethod() {
           System.out.println("This will execute Before Method");
     }
 
     @AfterMethod
     public void afterMethod() {
           System.out.println("This will execute After Method");
     }
 
     @BeforeClass
     public void beforeClass() {
           System.out.println("This will execute Before Class");
     }
 
     @AfterClass
     public void afterClass() {
           System.out.println("This will execute After Class");
     }
 
     @BeforeTest
     public void beforeTest() {
           System.out.println("This will execute Before Test");
     }
 
     @AfterTest
     public void afterTest() {
           System.out.println("This will execute After Test");
     }
 
     @BeforeSuite
     public void beforeSuite() {
           System.out.println("This will execute Before Suite");
     }
 
     @AfterSuite
     public void afterSuite() {
           System.out.println("This will execute After Suite");
     } 
}

Output
 
This will execute Before Suite
This will execute Before Test
This will execute Before Class
This will execute Before Method
This is Test Case 1
This will execute After Method
This will execute Before Method
This is Test Case 2
This will execute After Method
This will execute After Class
This will execute After Test
PASSED: testCase1
PASSED: testCase2

Execution process is as follows:

  1. First of all, beforeSuite() method is executed only once.

2. Lastly, the afterSuite() method executes only once.

3. @BeforeMethod and @AfterMethod are executed twice, one for Test Case 1 and again for Test Case 2.

4. Methods beforeTest(), beforeClass(), afterClass(), and afterTest() methods are executed only once.

5. This is all about TestNG Annotations.

6. To execute this program, we need to Right click and select Run as – TestNG

 The test execution result will look like something shown below

TestNG generates various type of reports under test-output folder.

Open ‘emailable-report.html‘, as this is a html report open it with browser. It will look like something below.

TestNG also produce “index.html” report and it resides under test-output folder

TestNG Interview Questions 2021

 HOME

 

TestNG.PNG

1. What is TestNG?

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use. The software testers to efficiently run the automated test scripts created in Selenium Webdriver use TestNG. Its full form is the “Testing New Generation” framework. It is use mostly to assert the results in an Automated Script as well as generate reports for test execution. 

For more details, click here

2. How TestNG can be install in Eclipse?

Follow the below steps to install TestNG on Eclipse:

  1. Launch Eclipse and go to Help option present at the top and select -“Install New Software”
  2. A dialog box will appear, click on Add button
  3. A new dialog box will appear. Mention Name as TestNG and location as “http://beust.com/eclipse/”  and click on Add button.
  4. Check the TestNG checkbox and click on the “Next” action button. The installation will start and the Eclipse will restart after installation.
  5. To verify if TestNG is installed successfully or not, go to Window, select Show View and then Other. Select Java and see within Java folder, you will see TestNG. This shows that TestNG is successfully install on the machine
  6. Right-click on the project in Eclipse -> Select build path -> Configure Build Path.
  7. Select the library tab -> Click on Add library button -> Select TestNG-> Click on Next -> Click on Finish and Apply and close.

For more details, click here

3. What is the sequence of execution of the annotations in TestNG?

The Sequence of execution of the annotations is as follows:

@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@Aftertest
@AfterSuite

For more details,click here

4. What is the importance of testng.xml file?

The testng.xml file is important because of the following reasons:

  1. It defines the order of the execution of all the test cases.
  2. It allows you to group the test cases and can be execute as per the requirements by mentioning 

groups = { “e2etest”“integerationtest” }

  1. It executes the selected test cases. It can disable the test cases which we don’t want to execute

@Test(enabled = false)

  1. In TestNG, listeners can be implemented at the suite level by adding below in xml

listenerclass-name =“com.selenium.testng.ListenerDemo

  1. It helps to integrate the TestNG framework with tools such as Jenkins.
  2. It supports parallel testing means provides multiple ways to execute tests in separate threads.

suitename=“TestSuite”thread-count=“3”parallel=“methods

  1. It allows for cross browser testing which means a web application tests on different browsers and operating systems. Here, mention different browser name in parameter.

<parameter name=”browser” value=”Edge” /> 

5. What are the types of Asserts in TestNG?

There are two types of assert in TestNG – Hard Assert and Soft Assert

Hard Assert: Hard Assert is the normal assert which is use to do validations in the TestNG class.

We have to use Assert class for hard assert as follows:

Assert.assertEquals(actual value, expected value);

If the hard assert fails, then none of the code is executed after the assert statement.

Soft Assert: If we want to continue the test execution even after the assert statement fails, then we have to use soft assert.

To create a soft assert, we have to create an object of a “softAssert” class as follows:

softAssert soft_assert = new softAssert();
soft_assert.assertAll();

So now if the test case fails, the execution is not terminate when we use soft assert.

For more details, click here

6.  What is TestNG Assert and list out some common Assertions supported by TestNG?            

TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception. Some of the common assertions supported by TestNG are

assertEqual(String actual,String expected)
assertEqual(String actual,String expected, String message)
assertEquals(boolean actual,boolean expected)
assertTrue(condition)
assertTrue(condition, message)
assertFalse(condition)
assertFalse(condition, message)

For more details, click here                                             

7. How to run a group of test cases using TestNG?

Groups are specified in your testng.xml file and can be found either under the  or  tag. Groups specified in the  tag apply to all the  tags underneath.

Test Case 1
     @Test (groups = { "smokeTest", "functionalTest" })
            public void loginTest(){
                System.out.println("Logged in successfully");
           }

Test Case 2
     @Test (groups = { "functionalTest" })
            public void loginTest(){
                System.out.println("Logged in successfully");
           }

TestNG.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "configureselenium">
  <test name = "TestNG Demo">
      <groups>
         <run>
              <include name = "e2etest" />
          </run>
        </groups>
    <classes>
          <class name = "TestNGDemo.TestNGGroupDemo1" />
         <class name = "TestNGDemo.TestNGGroupDemo2" />
     </classes>  
   </test>
</suite>

For more details, click here

     8. How to set test case priority in TestNG?

     We use priority attribute to the @Test annotations.  If no priority assigned to a Test Case, then the annotated test methods are, execute as per the alphabetical order of the tests

import org.testng.annotations.*;
     public class PriorityTestCase{
           @Test(priority=0)
            public void testCase1() {  
                        system.out.println("Test Case 1");
            }
            @Test(priority=1
            public void testCase2() {  
                        system.out.println("Test Case 2");
               }
      }

For more details, click here

9. How can we make one test method dependent on others using TestNG?

Using the dependsOnMethods parameter inside @Test annotation in TestNG we can make one test method run only after the successful execution of the dependent test method. Dependency is a feature in TestNG that allows a test method to depend on a single or a group of test methods. Method dependency only works if the “depend-on-method” is part of the same class or any of the inherited base classes (i.e. while extending a class)

         @Test
            public static void FirstTest() {
                        System.out.println("This is Test Case 1");
            }  
 
          @Test(dependsOnMethods = "FirstTest") 
             public static void SecondTest() {
                        System.out.println("This is Test Case 2 and will be executed after Test Case 1 sucessfully executed");
            } 

           @Test 
           public static void ThirdTest() {
                       System.out.println("This is Test Case 3");
             }  
 
           @Test 
             public static void FourthTest() {
                            System.out.println("This is Test Case 4"); 
         }
}

For more details, click here

10. How can we set the priority of test cases in TestNG?

Using the priority parameter in @Test annotation in TestNG we can define the priority of test cases. The default priority of the test when not specified is integer value 0. Example,

@Test(priority = 1)

For more details, click here

11. How to skip a method or a code block in TestNG?

If you want to skip a particular test method, then you can set the ‘enabled’ parameter in test annotation to false.

@Test(enabled = false) 

By default, the value of ‘enabled’ parameter will be true. Hence, it is not necessary to define the annotation as true while defining it.

For more details, click here

12. How do you define groups in TestNG?

TestNg allows us to group test methods that is not present in JUnit. We can declare the methods belong to groups as well as specify groups that contain other groups. To group test cases, we need to create testng.xml. 

@Test(groups = { "e2etest", "integerationtest" }) 

Testng.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
  <test name = "Test Demo">
      <groups>
         <run>
              <include name = "e2etest" />
          </run>
        </groups>
    <classes>
          <class name = "TestNGDemo.TestNGGroupDemo" />
     </classes>  
   </test>
</suite>

For more details, click here

13. How do you exclude a group from the test execution cycle?

Excluding a group in TestNG denotes that this particular group refrains from running during the execution, and TestNG will ignore it. Additionally, the name of the group that we want to exclude is defined in the XML file by the following syntax:

<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
   <test name = "Test Demo"> 
      <groups>
         <run>
            <exclude name = "e2etest"/>
         </run>
      </groups>
      <classes>
         <class name = "com.selenium.testng.TestNGDemo.TestNGGroupDemo"/>
      </classes>   
   </test>
</suite>

By putting our group “e2etest” inside the exclude tag, we are requesting TestNG to ignore the test cases under the group “e2etest”.

14. How to run test cases in parallel using TestNG?

In testng.xml, if we set ‘parallel’ attribute on the tag to ‘methods’, testNG will run all the ‘@Test’ methods in tag in a separate thread.

The parallel attribute of suite tag can accept four values:

tests – All the test cases inside tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute parallel but two methods of two different instances will run in different thread.

Below is an example to testng.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" thread-count="3" parallel="methods" >
<test name="GoogleTest">
<classes>
<class name="TestNGDemo.ParallelTestDemo">
</class>
</classes>
</test>
</suite>

For more details,click here

15. What is the use of @Listener annotation in TestNG?

Listener is define as interface that modifies the default TestNG’s behavior. It allows customizing TestNG reports or logs. There are many types of TestNG  listeners available. Here are a few listeners:

  • IAnnotationTransformer 
  • IAnnotationTransformer2 
  • IHookable 
  • IInvokedMethodListener 
  • IMethodInterceptor 
  • IReporter 
  • ISuiteListener 
  • ITestListener 

For more details,  click here

16. How are listeners declared in TestNG?

When you implement one of these interfaces, you can let TestNG know about it with either of the following ways:

  • Using in yourtestng.xml file.
@Listeners(com.selenium.testng.TestNGDemo.ListenerDemo.class)

Using the@Listeners annotation on any of your test classes.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "TestSuite">
<listeners>
<listener class-name ="com.selenium.testng.TestNGDemo.ListenerDemo"/>
</listeners>
 
<test name ="Test">
<classes>
<class name="com.selenium.testng.TestNGDemo.ListenerTestCases"/>
</classes>
</test>
</suite>

For more details, click here

17. Do TestNG reports need external code to write?

No, there is no need to write any code to generate reports in TestNG. In other words, the reports generation happens by default.

18. What are the two ways to generate a report in TestNG?

We can generate the TestNG reports in two ways:

· Emailable Reports
· Index Reports

19. Where is the emailable report generate and saved in TestNG?

Emailable reports generate under the project folder and test-output subfolder. This report is available as “emailable-report.html” by default.

20. Where is the index report generate and saved in TestNG?

The index report generates under the project folder and test-output subfolder. Moreover, this report is available as “index.html” by default.

21. What is invocationCount in TestNG?

An invocationCount in TestNG is the number of times that we want to execute the same test.

import org.testng.annotations.Test;
public class InvocationCountDemo {
            @Test(invocationCount = 5)
            public void testcase1() {
                        System.out.println("testcase1");
            } 
}

Output
testcase1
testcase1
testcase1
testcase1
testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1
PASSED: testcase1

22. How to pass the parameter in test case through testng.xml file?

TestNG has the ability to pass different test data to a test case as arguments that is called parametrization

@Parameters("value")

TestNG.xml looks like as shown below. Here, parameter name is browser name value for browser is “Chrome”. So, this “Chrome” value is pass to Test as parameter and as a result a Google Chrome browser opens.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "TestSuite">
  <test name="ChromeTest">
<parameter name="browser" value="Chrome" />
<classes>
<class name="com.selenium.testng.TestNGDemo.TestNGParameterizationDemo">
</class>
</classes>
</test> 
</suite>

For more details, click here