In one of our previous post we have seen what is dataProvider and how to write the syntax and also how we can get the object array to tests.
In this post, we will see how we can use this concept into our selenium tests.
We will use 2 different sets of login credentials [valid and invalid] and then run the same test multiple times and validate the login.
Video demo –
We will use 3 parameters for the login test,
- type which will tell if the current login data is valid or invalid
- username
- password
Based on the type, we will validate the login credentials in code.
@DataProvider(name = "data-set") public static Object[][] DataSet(){ //read the jason or excel data Object[][] obj = { {"valid", "standard_user", "secret_sauce"}, {"invalid", "standard_user", "123"} }; return obj; }
We will use the saucedemo.com website to login
Complete code –
package testNgLearning; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.time.Duration; public class DataProv_Selenium { WebDriver driver; @DataProvider(name = "data-set") public static Object[][] DataSet(){ //read the jason or excel data Object[][] obj = { {"valid", "standard_user", "secret_sauce"}, {"invalid", "standard_user", "123"} }; return obj; } @Test(dataProvider = "data-set") public void DataProvSampleTest(String type, String username, String password) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "/Users/skpatro/sel/chromedriver"); System.out.println(type + " " + username + " " + password); driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3)); driver.get("https://www.saucedemo.com/"); driver.findElement(By.id("user-name")).sendKeys(username); driver.findElement(By.id("password")).sendKeys(password); driver.findElement(By.id("login-button")).click(); if(type.equals("valid")){ wait.until(ExpectedConditions.presenceOfElementLocated( By.cssSelector("[class='title']"))); }else wait.until(ExpectedConditions.presenceOfElementLocated( By.cssSelector("[data-test='error']"))); Thread.sleep(2000); driver.quit(); } }
Our test method will run twice as the testdata from the dataProvider method has 2 sets of data.
1st run for the valid login credentials and 2nd run for invalid credentials.
The if condition actually validates the valid and invalid scenario.
For the valid login, we will validate the Product screen with cssSelector – [class=’title’]
For the invalid login, we will getting the error text on login screen itself, cssSelector – [data-test=’error’]
Hope this helps!
2 Comments