Create a class for the DataProvider method.
DataProvider Class:
import org.testng.annotations.DataProvider;
public class DataProviderDemo {
@DataProvider(name = "testData", parallel=true)
public Object[][] dataProvFunc() {
return new Object[][] {
{"","","Username cannot be empty"},
{"","Test","Username cannot be empty"},
{"$%1234","2345%$","Invalid credentials"}
};
}
}
An extra parameter “parallel” is required to initiate parallel execution in TestNG using the data provider.
A new ThreadLocal is instantiated for each test class since it’s in the BeforeClass annotation.
private static final ThreadLocal<WebDriver> WEB_DRIVER_THREAD_LOCAL = new ThreadLocal<WebDriver>();
Below is the complete test code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DataProviderParallelTests {
public WebDriver driver;
private static final ThreadLocal<WebDriver> WEBDRIVER_THREADLOCAL = new ThreadLocal<WebDriver>();
@BeforeMethod
public void setUp(){
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Vibha\\Software\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
WEBDRIVER_THREADLOCAL.set(driver);
System.out.println("Before method Thread Id:" + Thread.currentThread().getId());
}
@Test(dataProvider = "testData", dataProviderClass = DataProviderDemo.class)
public void invalidLoginTest(String username, String password, String errorMessage) throws InterruptedException {
driver = WEBDRIVER_THREADLOCAL.get();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/");
Thread.sleep(2000);
driver.findElement(By.name("txtUsername")).sendKeys(username);
System.out.println("Username :" + username);
Thread.sleep(2000);
driver.findElement(By.name("txtPassword")).sendKeys(password);
System.out.println("password :" + password);
Thread.sleep(2000);
String expectedError = driver.findElement(By.id("spanMessage")).getText();
System.out.println("Error Message :" + expectedError);
Assert.assertTrue(expectedError.contains(errorMessage));
}
@AfterMethod
public void tear_down() {
WebDriver driver = WEBDRIVER_THREADLOCAL.get();
System.out.println("After method Thread Id:" + Thread.currentThread().getId());
if (driver != null) {
driver.quit();
}
}
}
testng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" thread-count="2" data-provider-thread-count="2">
<test name="Test">
<classes>
<class name="DataProvider.DataProviderParallelTests"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
In this file, data-provider-thread-count is set to 2, then two browsers will be opened, and the first two tests will run from the list.
No comments:
Post a Comment