使用mockito进行文件系统模拟

时间:2018-03-26 19:06:27

标签: java hadoop mockito junit4

我是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迭代器。

如何实现这一目标?请帮助。

1 个答案:

答案 0 :(得分:1)

移动此行:

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

在调用metod 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语句,您可以在其中指示模拟对象在调用时必须返回的内容。