如果您需要任何其他信息,请告诉我。
简短版本:
使用 jUnit 4.12 进行测试时,这行代码会导致 NullPointerException:
File[] files = new File(searchPath).listFiles();
长版:
首先,这是环境:
- 操作系统:Win7 Pro(Netbeans 以管理员身份运行)
- IDE:Netbeans 8.0.2
- 构建自动化工具:Gradle
- Java:JDK 1.8
- 测试框架:jUnit 4.12
仅当我运行 jUnit-tests 时才会发生异常。 当我在没有任何测试的情况下构建它时,一切正常,并且来自 File[] files = new File(searchPath).listFiles() 的函数 listFiles() 不会返回空。
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;
}
最佳答案
documentation for File.listFiles()
包括:
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
看起来这就是正在发生的事情。 d:\..\core\files
的路径对我来说看起来不是一个有效的路径名...你怎么能期望一个目录成为根目录的父目录?
您需要更改测试以提供有效路径 - 并且很可能更改您的方法以应对可能返回 null
的 listFiles()
。
关于java - jUnit 使用 File 函数时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32783510/