如果您需要任何其他信息,请让我知道。当使用文件函数时,jUnit获取NullPointerException
短版本:
时使用JUnit 4.12测试的这行代码导致NullPointerException异常:
File[] files = new File(searchPath).listFiles();
龙版本:
首先,这是环境:
- OS:Win7的临(Netbeans的运行作为管理员)
- IDE:Netbeans的8.0.2
- 构建自动化工具:摇篮
- 的Java:JDK 1.8
- 测试框架:JUnit的4.12
只有当我运行jUnit测试时才会发生异常。 当我建立它没有任何测试,一切正常,功能listFiles() from File [] files = new File(searchPath).listFiles()不返回null。
gradle clean & gradle build -x test & gradle rest:jettyRun 2> test.txt
这是解决问题的功能,堪称我的类的构造函数:
/**
* Scans for JSON files on given path
* @param searchPath full path given
* @return String[] with the full paths and names of found files
*/
private String[] scanForJsons(String searchPath){
System.out.println("search path "+searchPath); // shows D:\..\core\files
File[] files = new File(searchPath).listFiles(); // problem line, allways returns null
System.out.print(((files!=null)?"Not null" : "Null"));
System.out.println("files.length: "+files.length);
String[] stringArray = new String[files.length];
for(int i = 0; i < files.length; i++){
String path = files[i].getName();
if (path.endsWith(".json")) {
path = path.substring(0, path.length() - 5);
}
stringArray[i] = path;
}
return stringArray;
}
现在还不清楚有问题的线路是否*收益* NULL或抛出一个例外。你的文字说了一件事,评论说另一件事。另外,请提供有问题的单元测试。 –