How to Parameterize Your Tests Using Selenium WebDriver?

How to Parameterize Your Tests Using Selenium WebDriver?

Dear Ariyashkumar,

Parameterizing your tests using Selenium WebDriver can be done in various ways to ensure your tests are more flexible and maintainable. Using TestNG DataProvider:

  1. Use TestNG’s @DataProvider annotation to provide different data sets to your test methods.
  2. Create a method that returns a two-dimensional array of objects representing different input data sets.
  3. Use the @Test annotation with the dataProvider attribute to link your test method to the DataProvider.

Example: @DataProvider(name = “loginData”) public Object[][] dataProviderMethod() { return new Object[][] { {“user1”, “pass1”}, {“user2”, “pass2”} }; }

@Test(dataProvider = “loginData”) public void testLogin(String username, String password) { // Use username and password in your test }

To learn more about TestNG Parameterization, follow this blog:Parameterization In TestNG - DataProvider and TestNG XML (With Examples).

Ariyashkumar,

Using JUnit Parameterized Tests

  1. Use JUnit’s @RunWith(Parameterized.class) annotation to indicate that the test should run with a parameterized runner.

  2. Implement a @Parameters method that returns a collection of arrays. Each array contains a set of parameters for one execution of the test.

  3. Create a constructor in your test class that takes the parameters as arguments.

@RunWith(Parameterized.class) public class LoginTest {

private String username;
private String password;

public LoginTest(String username, String password) {
    this.username = username;
    this.password = password;
}

@Parameterized.Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} });
}

@Test
public void testLogin() {
    // Use username and password in your test
}

}

To learn more about JUnit parameterize follow this blog on : JUnit Parameterized Test Using Selenium : With Examples | LambdaTestJUnit Parameterized Test Using Selenium : With Examples | LambdaTest

Hello Ariyaskumar,

Using External Data Sources (CSV, Excel)

  1. Store your test data in an external file, such as CSV or Excel.
  2. Use libraries like Apache POI for Excel or OpenCSV for CSV files to read data from the file.
  3. Read the data in your test initialization method and use it to parameterize your tests. Example: @DataProvider(name = “loginData”) public Object[][] readDataFromCSV() throws IOException { List<Object[]> data = new ArrayList<>(); try (CSVReader reader = new CSVReader(new FileReader(“loginData.csv”))) { String[] line; while ((line = reader.readNext()) != null) { data.add(line); } } return data.toArray(new Object[0][]); }

@Test(dataProvider = “loginData”) public void testLogin(String username, String password) { // Use username and password in your test }