使用MRUnit写一个单元测试

        MapReduce的map和reduce函数可以很容易的单独测试。MRUnit是一个测试库,可以很

容易的把已经输入传给map或reduce,并且验证输出是否是预期的。MRUnit与一个标准测试

框架一起使用,例如JUnit,所以你可以在普通的开发环境运行你的mapreduce job测试。例如,

下面描述的所有测试都可以在依照前面指导建立的集成开发环境运行。


Mapper

        例6-5显示了map的测试。

//Example 6-5. Unit test for MaxTemperatureMapper
import java.io.IOException;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.junit.*;
public class MaxTemperatureMapperTest {
    @Test
    public void processesValidRecord() throws IOException, InterruptedException {
        Text value = new Text("0043011990999991950051518004+68750+023550FM-12+0382" +
                                      // Year ^^^^
        "99999V0203201N00261220001CN9999999N9-00111+99999999999");
                              // Temperature ^^^^^
        new MapDriver<LongWritable, Text, Text, IntWritable>()
        .withMapper(new MaxTemperatureMapper())
        .withInput(new LongWritable(0), value)
        .withOutput(new Text("1950"), new IntWritable(-11))
        .runTest();
    }
}
        测试很简单,传递一条记录做为map的输入,检查输出的年份和温度。

        因为我是测试map,所以使用MRUnit的MapDriver,在调用runTest()方法执行测试之前,我们配置了

测试的mapper(MaxTemperatureMapper),及输入键值,期望的输出键(一个Text对象代表年份,1950)

和期望输出值(一个IntWritable代表温度,-1.1  °C)。如果mapper没有得到正确的输出,MRUnit测试失败。

注意输入的键可以设置为任意值,因为我们的mapper会忽略它。

          例6-6中,我们创建了一个Mapper的实现。由于在本章中我们要改进它,每一个版本放在不同的包中

表明它的版本以便于查看。例如,v1.MaxTemperatureMapper是版本1的MapTemperatureMapper。当然,在

实际中,你改进类型时不必把它们放到不同的包中。

//Example 6-6. First version of a Mapper that passes MaxTemperatureMapperTest
public class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
	@Override
	public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
		String line = value.toString();
		String year = line.substring(15, 19);
		int airTemperature = Integer.parseInt(line.substring(87, 92));
		context.write(new Text(year), new IntWritable(airTemperature));
	}
}
        这是个非常简单的实现,把年份和温度字段从字符串中取出并写到Context中。让我们添加一个测试,来测试

值丢失的情况,在原始数据中由+9999表示:

@Test
public void ignoresMissingTemperatureRecord() throws IOException,InterruptedException {
	Text value = new Text("0043011990999991950051518004+68750+023550FM-12+0382" +
	                              // Year ^^^^
	"99999V0203201N00261220001CN9999999N9+99991+99999999999");
	                      // Temperature ^^^^^
	new MapDriver<LongWritable, Text, Text, IntWritable>()
	.withMapper(new MaxTemperatureMapper())
	.withInput(new LongWritable(0), value)
	.runTest();
}
        MapDriver可以检查0个,1个或多个输出,由调用withOutput()方法的次数决定。在我们的应用中,因为丢失温度的

记录应该过滤掉,所以这个测试断定这个输入不产生输出。

        新的测试失败了,因为+9999并没有做为一个特殊情况。我们不在mapper中添加更多的逻辑代码,而是创建一个解析

类来封装逻辑,这样更有意义;见例6-7.

//Example 6-7. A class for parsing weather records in NCDC format
public class NcdcRecordParser {
    private static final int MISSING_TEMPERATURE = 9999;
    private String year;
    private int airTemperature;
    private String quality;

    public void parse(String record) {
        year = record.substring(15, 19);
        String airTemperatureString;
        // Remove leading plus sign as parseInt doesn't like them (pre-Java 7)
        if (record.charAt(87) == '+') {
            airTemperatureString = record.substring(88, 92);
        } else {
            airTemperatureString = record.substring(87, 92);
        }
        airTemperature = Integer.parseInt(airTemperatureString);
        quality = record.substring(92, 93);
    }

    public void parse(Text record) {
        parse(record.toString());
    }

    public boolean isValidTemperature() {
        return airTemperature != MISSING_TEMPERATURE
                && quality.matches("[01459]");
    }

    public String getYear() {
        return year;
    }

    public int getAirTemperature() {
        return airTemperature;
    }
}
        这样mapper(版本2)就更简单了(见例6-8)。它仅仅是调用了parser的parse()方法,parser会

把感兴趣的字段从输入中解析出来,使用isValidTemperature()方法检查温度是否合法,并且,如果合法,

使用parser的get方法取得年份和温度。注意,在isValidTemperature方法中,我们在检查温度是否缺失

的同时,检查了质量码字词来过滤掉不合理的温度取数。

//Example 6-8. A Mapper that uses a utility class to parse records
public class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    private NcdcRecordParser parser = new NcdcRecordParser();
    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        parser.parse(value);
        if (parser.isValidTemperature()) {
            context.write(new Text(parser.getYear()),
                    new IntWritable(parser.getAirTemperature()));
        }
    }
}


Reducer

        reducer要找到给定键的最大值。这里是这种特性的最简单的测试,使用ReduceDriver:

        @Test
	public void returnsMaximumIntegerInValues() throws IOException,InterruptedException {
		new ReduceDriver<Text, IntWritable, Text, IntWritable>()
		.withReducer(new MaxTemperatureReducer())
		.withInput(new Text("1950"),Arrays.asList(new IntWritable(10), new IntWritable(5)))
		.withOutput(new Text("1950"), new IntWritable(10)).runTest();
	}
        我们构造了一个有一些IntWritable值的list,然后验证MapTemperatureReducer是否能找出最大值。例6-9中的

代码是一个MaxTemperatureReducer的实现。

public class MaxTemperatureReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
	@Override
	public void reduce(Text key, Iterable<IntWritable> values, Context context)
			throws IOException, InterruptedException {
		int maxValue = Integer.MIN_VALUE;
		for (IntWritable value : values) {
			maxValue = Math.max(maxValue, value.get());
		}
		context.write(key, new IntWritable(maxValue));
	}
}





































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值