Dictionary 如何使用powermock捕获函数输入?
假设我有以下要测试的功能:Dictionary 如何使用powermock捕获函数输入?,dictionary,mapreduce,hbase,powermock,powermockito,Dictionary,Mapreduce,Hbase,Powermock,Powermockito,假设我有以下要测试的功能: boolean MyFunction (String input1, Text rowkey) { int a = 10; a = a + 10; return context.write(rowkey,a); } 请注意,context.write是一个写入数据库的函数 我想模拟该函数并检查传递给它的输入是否正确。我该怎么做 基本上,我可以做如下的事情(我似乎无法开始工作): PowerMockito.when(Context.write((Te
boolean MyFunction (String input1, Text rowkey) {
int a = 10;
a = a + 10;
return context.write(rowkey,a);
}
请注意,context.write是一个写入数据库的函数
我想模拟该函数并检查传递给它的输入是否正确。我该怎么做
基本上,我可以做如下的事情(我似乎无法开始工作):
PowerMockito.when(Context.write((Text)anyObject(),
(int)anyObject())。然后(compareResult(input1,input2));
专用应答比较结果(输入1、输入2){
AssertTrue(input1,this.Test1Input1AcceptanceCriteria)
AssertTrue(input2,this.Test1Input2AcceptanceCriteria)
}
您不需要这样做
假设上下文是封闭类的一个字段,那么“简单地”就必须找到一种方法,向测试中的类提供此类上下文对象的模拟版本
这里的典型方式:依赖项注入
比如:
然后,您可以编写单元测试,例如
@Test
public void testMyFunction() {
Context context = ... create some mock
Foo underTest = new Foo(context);
underTest.myFunction(...
使用上述方法,您对能力的所有需求都消失了。您可以使用“普通”模拟框架(如Mokito或EasyMock)来准备/验证您的上下文对象
你看,最后,你的问题是你创建的代码很难测试,除非你开始考虑依赖注入。如果你是认真对待测试的,看这些;它们为您提供了如何实际创建可测试代码的广泛介绍。这是我自己制定的解决方案,可以根据需要完美地工作。我使用这种技术有效地测试了我所有的map-reduce代码,而不需要mrunit的帮助
@Test
public void testMyFunction () throws Exception {
Context testContext = mock(Context.class);
MyFunction (input1, rowkey); // Call the function under test
// Now here is the magic. We use the verify technique to test
// the mocked class method while checking for equality with the acceptance criteria.
// In essence, the key is trap these underlying functions and ensure that
// they are passed in the right input from your function under test.
int expected_input_to_write = 10
Mockito.verify(testContext).write(eq((Object) new Text("test_string")), eq((Object) expected_input_to_write ));
}
@Test
public void testMyFunction() {
Context context = ... create some mock
Foo underTest = new Foo(context);
underTest.myFunction(...
@Test
public void testMyFunction () throws Exception {
Context testContext = mock(Context.class);
MyFunction (input1, rowkey); // Call the function under test
// Now here is the magic. We use the verify technique to test
// the mocked class method while checking for equality with the acceptance criteria.
// In essence, the key is trap these underlying functions and ensure that
// they are passed in the right input from your function under test.
int expected_input_to_write = 10
Mockito.verify(testContext).write(eq((Object) new Text("test_string")), eq((Object) expected_input_to_write ));
}