为什么我在此TestNG DataProvider注释方法中获得空指针?

时间:2012-07-19 05:44:58

标签: unit-testing junit testng

我遇到了这个TestNG DataProvider方法的问题。任何人都可以告诉我为什么会出现这个错误,并帮我修复这个课程?我无法插入数组。

我得到的错误含糊不清:

Caused by: java.lang.NullPointerException
    at tr.test.TestScript.createData(TestScript.java:55)

这是我的代码:

@SuppressWarnings("resource")
@DataProvider(name = "addresses")
public Object[][] createData() {
    Object[][] objs = new Object[100][];
    CSVReader reader = null;
    try {
        reader = new CSVReader( new FileReader("input.csv"), ',' );
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Object[] nextLine;
    int row = 0;
    try {
        while ( ( nextLine = reader.readNext() ) != null ) {
            System.out.println( "Adding test case " + (row+1) + ": " + nextLine[0] + ", " + nextLine[1] + ", " + nextLine[2] );
            objs[row][0] = nextLine[0]; //this is line #55
            objs[row][1] = nextLine[1];
            objs[row][2] = nextLine[2];
            row++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if ( objs == null ) {
        System.out.println("Error: Input file empty.");
        System.exit(0);
    }
    return objs;
}

1 个答案:

答案 0 :(得分:0)

因为您尚未初始化objs。就个人而言,我会建立一个ArrayList和:

return list.toArray();

此外,您需要添加到列表中的项目也需要初始化:

ArrayList<Object[]> = new ArrayList<Object[]>();
...
Object[] foo = new Object[2];
foo[0] = nextLine[0];
foo[1] = nextLine[1];
foo[2] = nextLine[2];
System.out.println( "Adding test case " + (i+1) + ": " + a + ", " + c + ", " + s );
list.add(foo);

...
Object[][] objs = new Object[list.size()][];

for (int i = 0; i < objs.length; i++) {
    objs[i] = list.get(i);
}

return objs;