模拟文件类和 NullPointerException
我正在使用 Mockito 创建一个文件模拟对象,该对象将用作存储新文件的目录。
Folder folder = Mockito.mock(File.class);
File file = new Agent().createNewFile(folder, "fileName");
在我的 Agent 类中:
public File createNewFile(File folder, String filename){
return new File(folder, "testfile");
}
但是在 createNewFile
方法中创建新文件时,我在 File 的初始化块处收到 NullPointerException:
java.lang.NullPointerException at java.io.File.<init>(File.java:308)
我认为发生这种情况是因为 File 没有任何空构造函数,所以当模拟对象时,某些内部状态保持为空。
我是否采用了错误的方法来模拟 Filefolder
对象?我的目标是在创建新文件之前检查一些约束,但我不想依赖文件系统上现有的真实文件夹。
谢谢。
I'm creating a File mock object with Mockito that will be used as the directory to store a new File.
Folder folder = Mockito.mock(File.class);
File file = new Agent().createNewFile(folder, "fileName");
and inside my Agent class:
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 createNewFile
method:
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.
Am I taking the wrong approach mocking the File folder
object? 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.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要定义文件夹的 getPath() 行为,因为它在 File 类中内部调用。
您可以这样做:
它只会在您没有真正创建新文件而仅调用 new File 时才起作用。
You need to define the behavior for getPath() for folder as it gets called internally in File class.
You can do it as:
It will work only till you don't really create a new file but only calling new File.