Bird
Raised Fist0
Selenium Javatesting~20 mins

DataProvider with external data in Selenium Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DataProvider Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of DataProvider with CSV external data
Given the following TestNG test code using a DataProvider that reads from a CSV file, what will be the output when the test runs?
Selenium Java
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class CsvDataProviderTest {

    @DataProvider(name = "csvData")
    public Object[][] readCsv() throws Exception {
        List<Object[]> data = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("testdata.csv"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                data.add(new Object[]{parts[0], Integer.parseInt(parts[1])});
            }
        }
        return data.toArray(new Object[0][]);
    }

    @Test(dataProvider = "csvData")
    public void testWithCsvData(String name, int age) {
        System.out.println(name + "-" + age);
    }
}
AJohn-30\nJane-25\nBob-40
BJohn-30\nJane-25\nBob-40\nnull-0
CCompilation error due to missing throws declaration
DRuntime error: NumberFormatException
Attempts:
2 left
💡 Hint
Think about how the CSV lines are read and parsed into the DataProvider array.
❓ assertion
intermediate
1:30remaining
Correct assertion for DataProvider test with Excel data
You have a TestNG test using a DataProvider that reads user credentials from an Excel file. Which assertion correctly verifies that the username is not empty in the test method?
Selenium Java
@Test(dataProvider = "excelData")
public void loginTest(String username, String password) {
    // assertion here
}
AAssert.assertTrue(username.length() > 0);
BAssert.assertFalse(username.isEmpty());
CAssert.assertNotNull(username);
DAssert.assertEquals(username, "");
Attempts:
2 left
💡 Hint
Check which assertion ensures the username string is not empty.
🔧 Debug
advanced
2:00remaining
Identify the error in DataProvider reading JSON file
This DataProvider reads test data from a JSON file. What error will occur when running this code?
Selenium Java
import org.testng.annotations.DataProvider;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONArray;
import org.json.JSONObject;

@DataProvider(name = "jsonData")
public Object[][] getData() throws Exception {
    String content = Files.readString(Paths.get("data.json"));
    JSONArray arr = new JSONArray(content);
    Object[][] data = new Object[arr.length()][2];
    for (int i = 0; i < arr.length(); i++) {
        JSONObject obj = arr.getJSONObject(i);
        data[i][0] = obj.getString("username");
        data[i][1] = obj.getString("password");
    }
    return data;
}
AArrayIndexOutOfBoundsException at runtime
BNullPointerException at runtime
CCompilation error due to missing return type
DNo error, runs successfully
Attempts:
2 left
💡 Hint
Check the for loop boundary condition carefully.
❓ framework
advanced
1:30remaining
Best practice for external DataProvider file location
In a Selenium TestNG project, where is the best place to store external test data files (like CSV, Excel) to ensure portability and easy access in DataProviders?
AIn a temporary folder outside the project
BIn the project root directory
CInside the src/main/java package folder
DInside src/test/resources folder
Attempts:
2 left
💡 Hint
Think about Maven/Gradle standard project structure and resource loading.
🧠 Conceptual
expert
1:30remaining
Why use external data sources with DataProvider?
Which is the main advantage of using external data sources (like CSV, Excel, JSON) with TestNG DataProviders instead of hardcoding test data inside the test class?
AIt reduces test execution time significantly
BIt guarantees zero test failures
CIt allows easy maintenance and scalability of test data without code changes
DIt automatically generates test reports
Attempts:
2 left
💡 Hint
Think about how test data changes affect test code.

Practice

(1/5)
1. What is the main purpose of using @DataProvider in Selenium tests?
easy
A. To locate web elements on the page
B. To create a new browser instance for each test
C. To generate test reports automatically
D. To run the same test multiple times with different input data

Solution

  1. Step 1: Understand the role of DataProvider

    @DataProvider is used to supply different sets of data to a test method so it can run multiple times with varied inputs.
  2. Step 2: Compare options with this purpose

    Only To run the same test multiple times with different input data describes running the same test multiple times with different data, which matches the purpose of DataProvider.
  3. Final Answer:

    To run the same test multiple times with different input data -> Option D
  4. Quick Check:

    DataProvider = multiple test runs with data [OK]
Hint: DataProvider runs tests repeatedly with varied inputs [OK]
Common Mistakes:
  • Confusing DataProvider with browser setup
  • Thinking DataProvider locates elements
  • Assuming DataProvider generates reports
2. Which of the following is the correct syntax to declare a DataProvider method that reads data from an external CSV file?
easy
A. @DataProvider(name = "csvData") public Object[][] getData() { // code to read CSV and return Object[][] }
B. @DataProvider public void getData() { // code to read CSV }
C. @DataProvider(name = "csvData") public void getData() { return new Object[][] {}; }
D. @DataProvider(name = "csvData") public Object getData() { // code to read CSV }

Solution

  1. Step 1: Check DataProvider method signature

    A DataProvider method must return Object[][] and be public. @DataProvider(name = "csvData") public Object[][] getData() { // code to read CSV and return Object[][] } matches this.
  2. Step 2: Verify other options

    @DataProvider public void getData() { // code to read CSV } returns void, which is invalid. @DataProvider(name = "csvData") public void getData() { return new Object[][] {}; } returns void but tries to return data, invalid. @DataProvider(name = "csvData") public Object getData() { // code to read CSV } returns Object, not Object[][], invalid.
  3. Final Answer:

    @DataProvider(name = "csvData") public Object[][] getData() { // code to read CSV and return Object[][] } -> Option A
  4. Quick Check:

    DataProvider method returns Object[][] [OK]
Hint: DataProvider must return Object[][] and be public [OK]
Common Mistakes:
  • Using void return type for DataProvider
  • Returning Object instead of Object[][]
  • Missing @DataProvider annotation name
3. Given the following DataProvider method reading CSV data, what will be the output when the test runs?
@DataProvider(name = "csvData")
public Object[][] getData() {
  return new Object[][] {
    {"user1", "pass1"},
    {"user2", "pass2"}
  };
}

@Test(dataProvider = "csvData")
public void loginTest(String username, String password) {
  System.out.println(username + ":" + password);
}
medium
A. user1 pass1 user2 pass2
B. user1:pass1 user2:pass2
C. user1pass1user2pass2
D. Compilation error due to DataProvider

Solution

  1. Step 1: Understand DataProvider data structure

    The DataProvider returns two sets of data: {"user1", "pass1"} and {"user2", "pass2"}.
  2. Step 2: Analyze test method output

    The test runs twice, printing username and password separated by a colon each time, resulting in two lines: "user1:pass1" and "user2:pass2".
  3. Final Answer:

    user1:pass1 user2:pass2 -> Option B
  4. Quick Check:

    Each data set prints username:password [OK]
Hint: Each data row runs test once, printing combined values [OK]
Common Mistakes:
  • Expecting all data printed in one line
  • Confusing array structure with output format
  • Assuming compilation error without reason
4. Identify the error in this DataProvider method that reads data from a CSV file:
@DataProvider(name = "csvData")
public Object[][] getData() {
  List lines = readCsv("data.csv");
  Object[][] data = new Object[lines.size()][];
  for (int i = 0; i <= lines.size(); i++) {
    data[i] = lines.get(i);
  }
  return data;
}
medium
A. The loop condition should be < instead of <= to avoid IndexOutOfBoundsException
B. The method should return List instead of Object[][]
C. The DataProvider annotation is missing parameters
D. The data array size is incorrect and should be lines.size() + 1

Solution

  1. Step 1: Analyze the for loop condition

    The loop runs from i = 0 to i <= lines.size(), which means it tries to access data[lines.size()] causing IndexOutOfBoundsException.
  2. Step 2: Correct the loop condition

    The loop should run while i < lines.size() to stay within valid array indices.
  3. Final Answer:

    The loop condition should be < instead of <= to avoid IndexOutOfBoundsException -> Option A
  4. Quick Check:

    Loop index must be less than array size [OK]
Hint: Loop index must be less than array length, not less or equal [OK]
Common Mistakes:
  • Using <= in loops causing index errors
  • Returning wrong data type from DataProvider
  • Misunderstanding DataProvider annotation usage
5. You want to use a DataProvider that reads test data from a CSV file and filters out rows where the first column is empty before running tests. Which approach correctly implements this?
hard
A. Return the entire CSV data as Object[][] without filtering, and filter inside the test method
B. Filter rows after test execution by skipping tests with empty first column
C. Read all CSV rows into a List, filter out rows with empty first column, then convert filtered list to Object[][] and return
D. Use a DataProvider that returns null for rows with empty first column

Solution

  1. Step 1: Understand filtering before test execution

    Filtering data in the DataProvider ensures only valid data sets run tests, keeping tests clean and efficient.
  2. Step 2: Implement filtering in DataProvider

    Read CSV into a list, remove rows with empty first column, then convert to Object[][] to supply filtered data to tests.
  3. Final Answer:

    Read all CSV rows into a List, filter out rows with empty first column, then convert filtered list to Object[][] and return -> Option C
  4. Quick Check:

    Filter data in DataProvider before tests run [OK]
Hint: Filter data inside DataProvider, not inside test method [OK]
Common Mistakes:
  • Filtering data inside test method instead of DataProvider
  • Returning null for filtered rows causing errors
  • Skipping tests after execution instead of filtering input
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard