本文地址:博客園 逖靖寒 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