使用mockito的java文件系统模拟

fjaof16o  于 2021-06-01  发布在  Hadoop
关注(0)|答案(1)|浏览(609)

我是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);

但我还是得到了空值。我想得到一个有效的remoteiterator迭代器。
如何做到这一点?请帮忙。

dgjrabp2

dgjrabp21#

移动此行:

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();

一般来说,可以定义mock whens 在做你想嘲笑的事之前。您必须准备模拟对象将返回的内容,然后定义 when 语句,指示模拟对象在调用时必须返回的内容。

相关问题