In our last topic we saw how to use the @Parameters
annotation. Now we are going to learn about @DataProvider
annotation.
In TestNG, there’s a concept known as data driven testing, which allows testers to automatically run a test case multiple times, with different input and validation values. A good example of this is, suppose, you have to test thousands of forms using automation. You’d want to pass complex parameters or parameters that need to be created from Java, in such cases parameters can be passed using Dataproviders.
In the below code, we are using @DataProvider
as a source for login credentials for Facebook. Test case will be executed twice as there are two sets of accounts provided for test.
File: DataProviderDemo.java
package TestNGDemo; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; import org.testng.annotations.DataProvider; public class DataProviderDemo { private static WebDriver driver; @DataProvider(name = "FB_Login") public static Object[][] credentials() { return new Object[][] { { "abc@gmail.com", "Test@123" }, { "def@gmail.com", "123@Test" }}; } // Here we are calling the Data Provider object with its Name @Test(dataProvider = "FB_Login") public void test(String uname, String password) { // Set path of Chrome Driver System.setProperty("webdriver.chrome.driver", "C:\\Files\\chromedriver.exe"); // Create a new instance of Chrome driver driver = new ChromeDriver(); // Open Google driver.navigate().to("https://www.facebook.com"); System.out.println("Logging in user: "+uname); // Find Search field WebElement user = driver.findElement(By.id("email")); // Type in keyword for search user.sendKeys(uname); WebElement pass = driver.findElement(By.id("pass")); // Type in keyword for search pass.sendKeys(password); // Prints in console // Clicks on search button driver.findElement(By.id("loginbutton")).click(); // Close Google Chrome driver.quit(); } }