简体   繁体   中英

FileSystem mocking using mockito

I am a newbie on Mockito. I wanted to test a method which has a line:

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

I have mocked filesystem instance here, and then i used the below :

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

But still i get the it as NULL. i want to get a valid RemoteIterator iterator.

How to accomplish that ? Pls help.

Move this line:

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

Before calling metod listFiles , and you have also have the content you want to this mock to return:

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

In general you define the mock whens before doing the stuff you want to mock. You have to prepare the content of what the mocked object will return, then you define the when statements where you instruct your mocked object what it has to return when called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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