逖靖寒的世界

每天进步一点点

导航

在Hadoop中使用MRUnit进行单元测试

本文地址:博客园 逖靖寒 http://gpcuster.cnblogs.com

前提

1. 了解JUnit4.x的使用。
2. 了解Mock的概念在单元测试中的应用。
3. 了解Hadoop中MapReduce的编程模型。

如果您对Junit和Mock不了解,可以先阅读[翻译]Unit testing with JUnit 4.x and EasyMock in Eclipse - Tutorial

如果您对Hadoop中MapReduce的编程模型不了解,可以先阅读Map/Reduce Tutorial

介绍

MRUnit是一款由Couldera公司开发的专门针对Hadoop中编写MapReduce单元测试的框架。

它可以用于0.18.x版本中的经典org.apache.hadoop.mapred.*的模型,也能在0.20.x版本org.apache.hadoop.mapreduce.*的新模型中使用。

官方的介绍如下:

MRUnit is a unit test library designed to facilitate easy integration between your MapReduce development process and standard development and testing tools such as JUnit. MRUnit contains mock objects that behave like classes you interact with during MapReduce execution (e.g., InputSplit and OutputCollector) as well as test harness "drivers" that test your program's correctness while maintaining compliance with the MapReduce semantics. Mapper and Reducer implementations can be tested individually, as well as together to form a full MapReduce job.

安装

在目前Hadoop的发行版中,并没有默认包含MRUnit。你需要去Couldera公司的官网中去下载一个由他们再次发行的版本。

推荐的版本为:hadoop-0.20.1+133.tar.gz

下载这个文件后,你将在hadoop-0.20.1+133\contrib\mrunit目录中找到我们需要的jar包:hadoop-0.20.1+133-mrunit.jar。

为了使用MRUnit,我们需要将hadoop-0.20.1+133-mrunit.jar和Junit4.x使用的jar包:junit.jar都添加到我们开发Hadoop程序项目的classpath中。

示例

代码是最好的文档,我们先看一个简单的map单元测试示例,代码如下:

package gpcuster.cnblogs.com;

import junit.framework.TestCase;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.lib.IdentityMapper;
import org.junit.Before;
import org.junit.Test;
import org.apache.hadoop.mrunit.MapDriver;

public class TestExample extends TestCase {

private Mapper<Text, Text, Text, Text> mapper;
private MapDriver<Text, Text, Text, Text> driver;

@Before
public void setUp() {
mapper = new IdentityMapper<Text, Text>();
driver = new MapDriver<Text, Text, Text, Text>(mapper);
}

@Test
public void testIdentityMapper() {
driver.withInput(new Text("foo"), new Text("bar"))
.withOutput(new Text("foo"), new Text("bar"))
.runTest();
}
}

在这段示例代码中,我们使用的map是org.apache.hadoop.mapred.lib.IdentityMapper。这是一个非常简单的map函数:输入什么,就输出什么。

org.apache.hadoop.mrunit.MapDriver是我们从MRUnit框架中导入的一个专门用于测试map的类。

我们通过withInput指定输入的参数,通过withOutput指定我们期望的输出,然后通过runTest运行我们的测试。

功能

1. 测试Map,我们可以使用MapDriver。
2. 测试Reduce,我们可以使用ReduceDriver。
3. 测试一个完整的MapReduce,我们可以使用MapReduceDriver。
4. 测试多个MapReduce组合而成的操作,我们可以使用PipelineMapReduceDriver。

实现

MRUnit框架非常精简,其核心的单元测试依赖于JUnit。

由于我们编写的MapReduce函数中包含有一个OutputCollector的对象,所以MRUnit自己实现了一套Mock对象来控制OutputCollector的操作。

局限

通过阅读MRUnit的源代码我们会发现:

1. 不支持MapReduce框架中的分区和排序操作:从Map输出的值经过shuffle处理后直接就导入Reduce中了。
2. 不支持Streaming实现的MapReduce操作。

虽然MRUnit有这些局限,但是足以完成大多数的需求。

参考资料

http://www.cloudera.com/hadoop-mrunit

 

本文地址:博客园 逖靖寒 http://gpcuster.cnblogs.com

posted on 2009-10-04 11:45  逖靖寒  阅读(9174)  评论(2编辑  收藏  举报