如何从csv文件中将参数传递给testng中的数据提供者

问题描述 投票:1回答:1

我从csv文件读取数据,我测试了这个数据将作为输入。我希望它作为每组价值的测试用例运行。因为我正在使用数据提供程序问题是,它只占用最后设置的数据行,请帮我调试代码

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

它只取最后一行name3 id3 text3并且只运行一次测试一次不是三次。

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


        }
java csv testng test-data testng-dataprovider
1个回答
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();
    }
推荐问答
热门问答
最新问答