繁体   English   中英

使用Mockito进行文件系统模拟

[英]FileSystem mocking using mockito

我是Mockito的新手。 我想测试一个有一行的方法:

RemoteIterator<LocatedFileStatus> it = fileSystem.listFiles(file, true);

我在这里模拟了文件系统实例,然后使用以下代码:

File sourceDirectory = temporaryFolder.newFolder("sourceDirectory");
Path sourceDirectoryPath = new Path(sourceDirectory.toString());
File hdfsFile1 = new File(sourceDirectory.getAbsolutePath().toString(), "hdfsFile1.txt");
File hdfsFile2 = new File(sourceDirectory.getAbsolutePath().toString(), "hdfsFile2.txt");
FileSystem fileSystem = Mockito.mock(FileSystem.class);
RemoteIterator<LocatedFileStatus> it = 
fileSystem.listFiles(sourceDirectoryPath, true);
when(fileSystem.listFiles(sourceDirectoryPath, true)).thenReturn(it);

但是我还是把它当作NULL。 我想获得一个有效的RemoteIterator迭代器。

如何做到这一点? 请帮助。

移动这一行:

when(fileSystem.listFiles(sourceDirectoryPath, true)).thenReturn(it);

调用梅托德之前listFiles ,你也有你想要这个模拟返回的内容:

//mock or provide real implementation of what has to be returned from filesystem mock
RemoteIterator<LocatedFileStatus> it = (RemoteIterator<LocatedFileStatus>) Mockito.mock(RemoteIterator.class);
LocatedFileStatus myFileStatus = new LocatedFileStatus();
when(it.hasNext()).thenReturn(true).thenReturn(false);
when(it.next()).thenReturn(myFileStatus).thenReturn(null);
//mock the file system and make it return above content
FileSystem fileSystem = Mockito.mock(FileSystem.class);
when(fileSystem.listFiles(sourceDirectoryPath, true)).thenReturn(it);

RemoteIterator<LocatedFileStatus> files =
        fileSystem.listFiles(sourceDirectoryPath, true);

assertThat(files.hasNext()).isTrue();
assertThat(files.next()).isEqualTo(myFileStatus);
assertThat(files.hasNext()).isFalse();

通常,您在执行要模拟的whens之前先定义模拟时间。 您必须准备模拟对象将返回的内容,然后定义when语句,以指示模拟对象在调用时必须返回的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM