Executing selenium tests in testng

To write Selenium tests, we will need to add below dependencies in TestNG project.
 
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
<scope>test</scope>
</dependency>
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;

@BeforeMethod
public void setup(){
  driver = new FirefoxDriver();
}

@AfterMethod
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 {
            FileUtils.copyFile(f,
                    new File("C:\Users\Sagar\IdeaProjects\TestNG-Project\abc.png"));
        }catch (Exception ex){
            System.out.println("exception " +ex.getMessage());
        }
    }
    driver.close();
    driver.quit();
}
}

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 {

@Test
public void test1(){
   driver.get("https://www.softpost.org");
    Assert.assertTrue(driver.getTitle().contains("My Tutorials"));
}
}                    

Web development and Automation testing

solutions delivered!!