Search code examples
dictionarymapreducehbasepowermockpowermockito

How do I trap a function inputs using powermock?


Lets say I have the function to test as below:

boolean MyFunction (String input1, Text rowkey) {
   int a = 10;
   a = a + 10;
   return context.write(rowkey,a);
}

Note that context.write is a function that writes to a database.

I would like to mock that function and check whether the inputs that are passed to it are correct. How do I do this?

Basically, can i do something like the below (which I cant seem to get to work):

   PowerMockito.when(Context.write((Text) anyObject(),
  (int) anyObject())).then(compareResult(input1,input2));

 private Answer<Boolean> compareResults(input1, input2) {
     AssertTrue(input1,this.Test1Input1AcceptanceCriteria)
     AssertTrue(input2,this.Test1Input2AcceptanceCriteria)
 }

Solution

  • Here is my solution that I worked out myself and works perfectly as I need it to. I test all my map-reduce code effectively with this technique without help from mrunit as well.

    @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 )); 
    }