文件系统到 FTPFile[]?
我只是想知道是否有办法模拟 FTPFile 数组。 我试图将一个假 FTPFile[] 作为参数传递给我想要测试的函数:
protected void indexFolder(FTPClient, FTPFile[], File, FTPFolderAssetSource);
我正在使用 FakeFtpServer 来伪造,正如名称所示,我的 ftp 服务器。该库允许以这种方式伪造 ftp 内容:
fileSystem = new WindowsFakeFileSystem();
DirectoryEntry directoryEntry1 = new DirectoryEntry("c:\\");
directoryEntry1.setPermissions(new Permissions("rwxrwx---"));
directoryEntry1.setOwner(USER1);
FileEntry fileEntry1 = new FileEntry("c:\\data\\file1.txt", CONTENTS);
fileEntry1.setPermissionsFromString("rw-rw-rw-");
fileEntry1.setOwner(USER1);
fileEntry1.setGroup(GROUP);
fileSystem.add(directoryEntry1);
fileSystem.add(fileEntry1);
ftp = new FakeFtpServer();
ftp.setFileSystem(fileSystem);
现在,我如何使用 fileSystem 来测试需要 FTPFile[] 作为参数的函数?
I simply want to know if there is a way to mock an array of FTPFile.
I am trying to pass as a parameter a fake FTPFile[] to the function I want to test:
protected void indexFolder(FTPClient, FTPFile[], File, FTPFolderAssetSource);
I am using FakeFtpServer to fake, as the name says, my ftp server. This library permit to fake the ftp content in this way:
fileSystem = new WindowsFakeFileSystem();
DirectoryEntry directoryEntry1 = new DirectoryEntry("c:\\");
directoryEntry1.setPermissions(new Permissions("rwxrwx---"));
directoryEntry1.setOwner(USER1);
FileEntry fileEntry1 = new FileEntry("c:\\data\\file1.txt", CONTENTS);
fileEntry1.setPermissionsFromString("rw-rw-rw-");
fileEntry1.setOwner(USER1);
fileEntry1.setGroup(GROUP);
fileSystem.add(directoryEntry1);
fileSystem.add(fileEntry1);
ftp = new FakeFtpServer();
ftp.setFileSystem(fileSystem);
Now, how can I use fileSystem to test my function who require FTPFile[] as parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
FTPFile
类没有什么特别之处可以防止模拟。不幸的是,使用 Mockito,你无法模拟数组,因为它们是最终的。此示例代码应该演示问题:
运行它,您将看到它产生一条错误消息,该消息明确说明了问题:
org.mockito.exceptions.base.MockitoException:
无法模拟/间谍类 [LTestMockArrays$Animal;
Mockito 无法模拟/间谍以下内容:
- 最后的课程
- 匿名类
- 原始类型
最简单的解决方案是使用 Mockito 的扩展,例如 Powermock通过使用字节码操作来绕过 Mockito 模拟能力的某些限制。然后,您可以通过将以下注释添加到 junit 测试类来创建模拟数组:
然后在您的测试方法中,您将像平常一样创建 Mockito 模拟:
There is nothing specialy about the
FTPFile
class which would prevent mocking. Unfortunately, using Mockito, you can not mock arrays, as they are final.This sample code should demonstrate the problem:
Run it, and you'll see it results in an error message which makes explicit the problem:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class [LTestMockArrays$Animal;
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
The easiest solution is to use an extension to Mockito like Powermock which gets around certain restrictions to Mockito's mocking ability by using bytecode manipulation. Then you could create the mock array by adding the following annotations to your junit test class:
then in your test method you would create Mockito mock as normal: