【问题标题】:FileSystem mocking using mockito使用 mockito 模拟文件系统
【发布时间】:2018-03-26 19:06:26
【问题描述】:

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

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

【问题讨论】:

    标签: java hadoop mockito junit4


    【解决方案1】:

    移动这一行:

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

    在调用metodlistFiles之前,你也已经有了想要这个mock返回的内容:

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

    【讨论】:

    • 但这会抛出错误,因为在那个阶段没有定义“它”。你不这么认为吗?
    • 对,我错过了注意到您的代码中的故障。我编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 2014-08-16
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多