Hadoop:如何对FileSystem进行单元测试

zoh*_*har 13 unit-testing hadoop

我想运行单元测试,但我需要一个org.apache.hadoop.fs.FileSystem实例.是否有任何模拟或任何其他解决方案来创建FileSystem?

Ale*_*rev 17

如果您正在使用hadoop 2.0.0及更高版本 - 请考虑使用hadoop-minicluster

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-minicluster</artifactId>
    <version>2.5.0</version>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

有了它,您可以在本地计算机上创建临时hdfs,并在其上运行测试.setUp方法可能如下所示:

baseDir = Files.createTempDirectory("test_hdfs").toFile().getAbsoluteFile();
Configuration conf = new Configuration();
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
hdfsCluster = builder.build();

String hdfsURI = "hdfs://localhost:"+ hdfsCluster.getNameNodePort() + "/";
DistributedFileSystem fileSystem = hdfsCluster.getFileSystem();
Run Code Online (Sandbox Code Playgroud)

在tearDown方法中,您应该关闭mini hdfs集群,并删除临时目录.

hdfsCluster.shutdown();
FileUtil.fullyDelete(baseDir);
Run Code Online (Sandbox Code Playgroud)


Arn*_*-Oz 7

看看hadoop测试罐

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-test</artifactId>
    <version>0.20.205.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

它已被归类为设置MiniDFSCluster和MiniMRCluster,因此您可以在没有hadoop的情况下进行测试


Ice*_*x13 5

为什么不使用像Mockito或PowerMock这样的模拟框架来模拟与FileSystem的交互?您的单元测试不应该依赖于实际的FileSystem,而应该只是在与FileSystem交互时验证代码中的行为.