Sunday, 22 March 2015

Parameterized Mocking with Powermock

@RunWith(Parameterized.class)
@PrepareForTest(Helper.class)
public class ParameterizedPowerMock {

 
 /**
  * @RunWith(PowerMockRunner.class)
  * 
  * The Main thing to look out for Here is the 
  * Parameterized Version of Powermock & @Rule
  * i.e. PowerMockRule.
  * 
  * For JUnit Parameterized Test cases the class
  * needs to be annotated with @RunWith(Parameterized.class)
  * and for Powermock the class needs to be annotated with
  * @RunWith(PowerMockRunner.class), so a Test class at the same
  * Time cannot be annotated with both @Runwith classes,
  * So we are using here @Rule
  * 
  * Two important points to be kept in mind for JUnit 4 Parameterized
  * Test cases with PoweMock is that, and Rule and Test Class Constructor
  * should be public
  * 
  */
 
 
 //@Rule should be declared Public
 
 public @Rule PowerMockRule rule = new PowerMockRule();
 
 String param;
 String expectedResult;
 
 //The constructor should be declared Public
 
 public ParameterizedPowerMock(String param, String expectedResult)
 {
  this.param =  param;
  this.expectedResult =  expectedResult;
 }
 
 @Parameterized.Parameters
 public static Iterable data1() {
  
  return Arrays.asList(new Object[][] { 
   {"asd|asd|||ASD||ASD","asd|asd|||ASD||ASD"},
   {"Subha","Subha"}
   
  });
 }
 
 @Test
 public void testParameterizedFlavourWithMockForPrivateNonStatic() throws Exception
 {
  
  Helper helper = PowerMockito.spy(new Helper());
  doAnswer(answerIsArgumentString()).when(helper,method(Helper.class,"formatDateTest",String.class)).withArguments(anyString());
  
  String actualResult = helper.invokePrivate(param);//new ExternalHelper().invoke(); 
  
  
  assertEquals(expectedResult, actualResult);
  
 }
 
 @Test
 public void testParameterizedFlavourWithMockForPrivateStatic() throws Exception
 {
  
  PowerMockito.spy(Helper.class);
  
  doAnswer(answerIsArgumentString()).when(Helper.class, method(Helper.class, "formatDateTestStatic",String.class)).withArguments(param);
  
  //PowerMockito.doReturn(param).when(Helper.class, "formatDateTestStatic", eq(param));
  
  String actualResult = Helper.invokePrivateStatic(param);//new ExternalHelper().invoke(); 
  
  assertEquals(expectedResult, actualResult);
  
 }
 
 
 private static Answer answerIsArgumentString() { 
    return new Answer() {
      public String answer(InvocationOnMock invocation) {
         String str = ((String)invocation.getArguments()[0]);
         return str;
      }
    };
  }
 
}


View Subhankar Paul's profile on LinkedIn

No comments:

Post a Comment