在TestNG中使用带有DataProvider的文本文件

时间:2014-02-21 13:20:20

标签: java testing testng dataprovider

我正在尝试使用带有dataProvider的TestNG对java程序进行一些测试。

当我手动填充dataProvider时,一切都很完美。现在我正在尝试使用带有数据提供程序的文本文件,其中每行都是测试的输入。我需要的不仅仅是打印每一行,我必须阅读每一行,操纵并生成预期结果。因此,对于每行我将发送到测试,行本身和预期结果。然后在测试中,该线将由程序测试并生成实际结果,以最终比较预期实际结果。

我已经做了第一次尝试,但它没有按照我的预期工作,而且性能非常差。

我在网上搜索,但我仍然找不到从数据文件(.txt)将数据绑定到dataProvider的正确方法

我目前的代码(简化)是:

@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;
  }

希望你能帮助我,谢谢

1 个答案:

答案 0 :(得分:3)

以下是一些示例代码,前提是您使用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
}
相关问题