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.openqa.selenium.chrome.ChromeDriver;
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;
 
 @BeforeClass
 public void setupClass() {
  
  // Set Chrome driver property
  System.setProperty("webdriver.chrome.driver", "D:\\mydir\\chromedriver.exe");
  
  // Launch chrome browser
  driver = new ChromeDriver();

  // Opening Browser URL and maximize it
  driver.get("http://www.techlistic.com/");
  driver.manage().window().maximize();
 }
 
 @BeforeMethod
 public void setupMethod() {
  // Webdriver Code for login

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

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

 }
 
 @AfterMethod
 public void teardownMethod() {
  // Webdriver Logout code

 }
 
 @AfterClass
 public void teardownClass() {
  // Close all webdriver instances
  driver.close()
  driver.quit()
 }
}


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



Subscribe to Facebook Group
Join our Telegram channel at https://t.me/techlistic
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Popular Posts

Top 20 Advanced Selenium Webdriver Coding Interview Questions of 2019

Top 10 Demo Websites to Practice Selenium Webdriver Online

Top 25 Must to know Selenium Webdriver Commands List

Selenium Essentials - How to become expert in Automation Testing?