【问题标题】:Why do I get a null pointer in this TestNG DataProvider annotation method?为什么我在这个 TestNG DataProvider 注释方法中得到一个空指针?
【发布时间】:2012-07-19 05:44:57
【问题描述】:

我遇到了这个 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;
}

【问题讨论】:

  • 我在代码中添加了注释来回答这个问题。

标签: unit-testing junit testng


【解决方案1】:

因为你还没有初始化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;

【讨论】:

  • 抱歉,这没用。这是一个带注释的方法,我相信它需要作为 Object[][] 返回。当我使用 ArrayList 时,它似乎窒息了。
  • @djangofan 添加了返回数组的其他方式。
猜你喜欢
  • 2019-07-25
  • 2011-12-13
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 2013-03-20
  • 1970-01-01
相关资源
最近更新 更多