通常情況下,我們需要用小數據集來單元測試我們寫好的map函數和reduce函數。而一般我們可以使用Mockito框架來模擬OutputCollector對象(Hadoop版本號小于0.20.0)和Context對象(大于等于0.20.0)。 下面是一個簡單的WordCount例子:(使用的是新API) 在開始之
通常情況下,我們需要用小數據集來單元測試我們寫好的map函數和reduce函數。而一般我們可以使用Mockito框架來模擬OutputCollector對象(Hadoop版本號小于0.20.0)和Context對象(大于等于0.20.0)。
下面是一個簡單的WordCount例子:(使用的是新API)
在開始之前,需要導入以下包:
1.Hadoop安裝目錄下和lib目錄下的所有jar包。
2.JUnit4
3.Mockito
?
map函數:
public class WordCountMapper extends Mapper { private static final IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException { String line = value.toString(); // 該行的內容 String[] words = line.split(";"); // 解析該行的單詞 for(String w : words) { word.set(w); context.write(word,one); } } }
?reduce函數:
public class WordCountReducer extends Reducer { @Override protected void reduce(Text key, Iterable values,Context context) throws IOException, InterruptedException { int sum = 0; Iterator iterator = values.iterator(); // key相同的值集合 while(iterator.hasNext()) { int one = iterator.next().get(); sum += one; } context.write(key, new IntWritable(sum)); } }
?測試代碼類:
public class WordCountMapperReducerTest { @Test public void processValidRecord() throws IOException, InterruptedException { WordCountMapper mapper = new WordCountMapper(); Text value = new Text("hello"); org.apache.hadoop.mapreduce.Mapper.Context context = mock(Context.class); mapper.map(null, value, context); verify(context).write(new Text("hello"), new IntWritable(1)); } @Test public void processResult() throws IOException, InterruptedException { WordCountReducer reducer = new WordCountReducer(); Text key = new Text("hello"); // {"hello",[1,1,2]} Iterable values = Arrays.asList(new IntWritable(1),new IntWritable(1),new IntWritable(2)); org.apache.hadoop.mapreduce.Reducer.Context context = mock(org.apache.hadoop.mapreduce.Reducer.Context.class); reducer.reduce(key, values, context); verify(context).write(key, new IntWritable(4)); // {"hello",4} } }
?
具體就是給map函數傳入一行數據-"hello"
map函數對數據進行處理,輸出{"hello",0}
reduce函數接受map函數的輸出數據,對相同key的值求和,并輸出。
原文地址:Hadoop之MapReduce單元測試, 感謝原作者分享。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com