我是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);
,但我仍然将其视为无效。我想获得有效的远程标生迭代器。
如何实现这一目标?请帮助。
移动此行:
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
语句,其中指示止模对象在调用时必须返回的内容。