java 模拟文件类和 NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3515011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock File class and NullPointerException
提问by manolowar
I'm creating a File mock object with Mockito that will be used as the directory to store a new File.
我正在使用 Mockito 创建一个 File 模拟对象,该对象将用作存储新文件的目录。
Folder folder = Mockito.mock(File.class);
File file = new Agent().createNewFile(folder, "fileName");
and inside my Agent class:
在我的 Agent 类中:
public File createNewFile(File folder, String filename){
return new File(folder, "testfile");
}
But I'm getting a NullPointerException at the initialization block of File when creating the new file inside createNewFilemethod:
但是在createNewFile方法中创建新文件时,我在 File 的初始化块处收到 NullPointerException :
java.lang.NullPointerException at java.io.File.<init>(File.java:308)
I think it happens because File doesn't have any empty constructor, so when mocking the object some internal state remains null.
我认为这是因为 File 没有任何空的构造函数,所以在模拟对象时,一些内部状态保持为空。
Am I taking the wrong approach mocking the File folderobject? My goal is to check some constraints before creating the new file, but I don't want to depend on an existing real folder on the file system.
我是否采取了错误的方法来嘲笑File folder对象?我的目标是在创建新文件之前检查一些约束,但我不想依赖于文件系统上现有的真实文件夹。
Thank you.
谢谢你。
采纳答案by Ankit Bansal
You need to define the behavior for getPath() for folder as it gets called internally in File class.
您需要为文件夹定义 getPath() 的行为,因为它在 File 类中被内部调用。
You can do it as:
你可以这样做:
File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");
It will work only till you don't really create a new file but only calling new File.
它只会在您没有真正创建新文件而仅调用新文件时才有效。

