Hadoop:如何进行单元测试FileSystem

问题描述:

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

看一看类Hadoop试验瓶

<dependency> 
    <groupId>org.apache.hadoop</groupId> 
    <artifactId>hadoop-test</artifactId> 
    <version>0.20.205.0</version> 
</dependency> 

它归类为建立MiniDFSCluster和MiniMRCluster所以你可以不Hadoop的

我做了什么(直到我会找到更好的解决方案)我扩展了FileSystem。

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

如果你正在使用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> 

有了它,你可以在你的本地计算机上的临时HDFS,并在其上运行测试。的设置方法可以是这样的:

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

而且在拆卸方法,你应该关闭你的小HDFS集群,并删除临时目录。

hdfsCluster.shutdown(); 
FileUtil.fullyDelete(baseDir); 

您可能想看看RawLocalFileSystem。尽管我认为你最好嘲笑它。

您可以使用HBaseTestingUtility

public class SomeTest { 
    private HBaseTestingUtility testingUtil = new HBaseTestingUtility(); 

    @Before 
    public void setup() throws Exception { 
     testingUtil.startMiniDFSCluster(1); 
    } 

    @After 
    public void tearDown() throws IOException { 
     testingUtil.shutdownMiniDFSCluster(); 
    } 

    @Test 
    public void test() throws Exception { 
     DistributedFileSystem fs = testingUtil.getDFSCluster().getFileSystem(); 
     final Path dstPath = new Path("/your/path/file.txt); 
     final Path srcPath = new Path(SomeTest.class.getResource("file.txt").toURI()); 
     fs.copyFromLocalFile(srcPath, dstPath); 
     ... 
    } 
}