Executing Selenium tests using TestNG

To write Selenium tests, we will need to add below dependencies in TestNG project.



Then we can create a Base Test class that has the definitions for @BeforeMethod and @AfterMethod. Note that we have instantiated the webdriver instance in @BeforeMethod and We have closed the webdriver in @AfterMethod. We have also written a code to take the screenshot in case of failure.

package org.softpost;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import java.io.File;

 * Created by Sagar on 26-06-2016.
public class BaseTest {
    WebDriver driver;

    public void setup(){
      driver = new FirefoxDriver();

    public void cleanup(ITestResult result){
        if (result.getStatus()==ITestResult.FAILURE){
            System.out.println("Test Failed");
            //Here we can take screen shot
            File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            try {
                        new File("C:\\Users\\Sagar\\IdeaProjects\\TestNG-Project\\abc.png"));
            }catch (Exception ex){
                System.out.println("exception " +ex.getMessage());

Below is the actual test Class. In this test, we are verifying the title of website – www.softpost.org

package org.softpost;

import org.testng.Assert;
import org.testng.annotations.Test;

public class SeleniumTests extends BaseTest {

    public void test1(){
        Assert.assertTrue(driver.getTitle().contains("My Tutorials"));

You may also like...