2014-09-25 59 views
1

正在从csv文件读取数据,我测试了这些数据将作为输入。 我希望它作为tes套件运行每一组值。对于正在使用的数据提供 的问题是,它是只取数据的最后一组行,请帮我调试的代码如何从csv文件传递参数给testng中的数据提供者

For eg : if my csv has following data 
name1 id1 text1 
name2 id2 text2 
name3 id3 text3 

它只取最后一行NAME3 ID3文字3和运行测试只有一次不是三次。

@DataProvider(name = "test") 
     public Object[][] provider() throws InterruptedException 
     { 

      Object[][] returnObject ; 

      String[] checkpoint = ReadfromCSV(); 

      count = count + 1; 

      returnObject = new Object[][]{checkpoint }; 
      return returnObject; 
     } 

     @Test(description = "Test", groups = "test" , dataProvider = "test") 
     public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11) { 

      System.out.println("1:" + val1); 

      System.out.println("4:" + val2); 

      System.out.println("5:" + val3); 


     } 
     @SuppressWarnings("null") 
     public String[] ReadfromCSV() throws InterruptedException { 


      String[] data= null; 
      String csvFile = "F:/sample1.csv"; 
      BufferedReader br = null; 
      String line = ""; 
      String cvsSplitBy = ","; 

      try { 

       br = new BufferedReader(new FileReader(csvFile)); 
       while ((line = br.readLine()) != null) { 

        // use comma as separator 
       data= line.split(cvsSplitBy); 




       } 

      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } finally { 
       if (br != null) { 
        try { 
         br.close(); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
      System.out.println("Done"); 
      return data; 


     } 

回答

4

您应该读取数据提供者的整个文件并返回测试用例的迭代器。这是数据提供者的一些伪代码。请注意,我使用List<String []>来存储测试用例,而不是Object [] []。这使您可以动态地定义测试用例。

@DataProvider(name = "test") 
    public Iterator<Object []> provider() throws InterruptedException 
    { 
     List<Object []> testCases = new ArrayList<>(); 
     String[] data= null; 

     //this loop is pseudo code 
     br = new BufferedReader(new FileReader(csvFile)); 
     while ((line = br.readLine()) != null) { 
      // use comma as separator 
      data= line.split(cvsSplitBy); 
      testCases.add(data); 
     } 

     return testCases.iterator(); 
    } 
+0

感谢您的回复,我没有得到您的想法。你可以在我的代码中进行更改并显示。 – Dude 2014-09-25 09:45:57

+0

@Dude我更新了我的答案。我怀疑你错过了TestNg只需调用一次数据提供者来准备多个测试运行的测试用例的事实。 – luboskrnac 2014-09-25 11:01:15

相关问题