2014-02-21 37 views
0

我正在嘗試使用TestNG和dataProvider爲java程序進行一些測試。在TestNG中使用DataProvider中的文本文件

當我手動填充數據提供程序,一切都運行完美。現在我試圖在數據提供程序中使用一個文本文件,其中每行都是測試的輸入。我需要的不僅僅是打印每一行,我必須讀取每一行,操作並生成一個預期結果。因此,我將發送每條線路到測試,線路本身和預期結果。然後在測試中該行將通過程序測試並生成實際結果,最後比較預期實際的結果。

我已經做出了第一次嘗試,但它不工作,我期待並表現真的很差。

我在網絡上搜索,但我仍然無法找到將數據綁定到一個文本文件中的數據提供程序文件(.txt)

我當前的代碼(簡化)正確的做法是:

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

希望你能幫助我,謝謝

+0

我你現在的代碼是? – fge

回答

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 
} 
+0

我會嘗試這種方式,我認爲這應該是我一直在尋找的。只有一件事,Paths.get(「whatever」)中的「wathever」應該替換爲我的文本文件的路徑,對吧? – Angelo

+0

是的。但是這是一個例子......我猜你的文件在類路徑中,所以在這種情況下,代碼將會不同。 – fge

+0

我看到你已經粘貼了你的代碼了...這裏的問題是你似乎在測試中複製了你的方法的邏輯。不是非常可行的imho ... – fge

相關問題