Selenium-TestNG Integration Explained with Coding Example

In this tutorial you will learn the real use of TestNG annotations covered in previous post with Selenium Webdriver scripts.

Selenium - TestNG integration program:

package com.techlistic.selenium;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNGAnnotations2 {
 WebDriver driver;
 public void setupClass() {
  // Set Chrome driver property
  System.setProperty("", "D:\\mydir\\chromedriver.exe");
  // Launch chrome browser
  driver = new ChromeDriver();

  // Opening Browser URL and maximize it
 public void setupMethod() {
  // Webdriver Code for login

 public void test_HomePage() {
  // Webdriver code to test some functionality on Home page

 public void test_UsersPage() {
  // Webdriver code to test some functionality on Users page

 public void teardownMethod() {
  // Webdriver Logout code

 public void teardownClass() {
  // Close all webdriver instances

Program Explanation:

1. @Test - This annotation is used with test methods.

2. @BeforeClass - If this annotation is used with some method then it would be executed only once before all test methods or you can say when the class is about to be executed then @BeforeClass executes. It is generally used for setup method for class. E.g.,
  • Let's say your class has 10 test methods
  • And you want to launch browser only once at the beginning and use the same browser instance for all test methods
  • Then launch browser in you setup_class method with @BeforeClass on top of it.
3. @BeforeMethod/@AfterMethod - Use this method for setup method to be called before every test. Like in above example, we are logging in before every test method and logging out after every method.

4. @AfterClass - Use this annotation for teardown class method. For e.g., in above example we used it for closing all the browser instances at the end of executing all the test methods.

Hope it helps!

TestNG Annotations  << Previous    ||    Next >>  Set Dependency inTestNG

Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.


Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Automate Browser Actions on using Selenium

Automate E-Commerce Website using Selenium Webdriver