Question

I'm trying to make some tests for a java program using TestNG with a dataProvider.

When I populate the dataProvider manually, everything works perfect. Now I'm trying to use a text file with the data provider where each line is the input for the test. I need more than just print each line, I have to read each line, manipulate and generate an expected result. So, for each line I will send to the test, the line itself and the expected result. Then in the test the line will be tested by the program and generate the actual result, to finally compare the expected and actual results.

I have made a first attempt, but it's not working as I expect and the performance is really poor.

I have search on the web, but I still can't find the correct way to bind data to a dataProvider from a text file (.txt)

my current code (simplified) is:

@DataProvider(name="fileData")
  public Object[][] testData() throws IOException {
      int numLines = 0;
      int currentLine = 0;
      String sended = "";
      File file = new File("file.txt");

      //counting lines from file
      BufferedReader br = new BufferedReader(new FileReader(file));
      while ((br.readLine()) != null){
          numLines++;
      }
      br.close();

      //extracting lines to send to test
      String[][] testData = new String[numLines][2];
      BufferedReader br2 = new BufferedReader(new FileReader(file));
      while ((sended = br2.readLine()) != null){
          String expected = sended.substring(50, 106) + "00" + sended.substring(106, 154); 
           testData[currentLine][0] = sended;
           testData[currentLine][1] = expected;
           currentLine++;
      }
      br2.close();
      return testData;
  }

Hope you can help me, thanks

Was it helpful?

Solution

Here is some sample code, provided you use Java 7:

@DataProvider
public Iterator<Object[]> testData()
    throws IOException
{
    final List<Object[]> list = new ArrayList<>();

    for (final String line: Files.readAllLines(Paths.get("whatever"),
        StandardCharsets.UTF_8)
        list.add(new Object[]{ line, process(line) };

    return list.iterator();
}

private static Whatever process(final String line)
{
    // whatever
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top