Wednesday, 26 July 2017

Whitebox: invoke instance method

Whitebox class provides the method 'invokeMethod', it is used to invoke the methods of an object (or) class. Following are the overloaded form of 'invokeMethod'.

public static synchronized <T> T invokeMethod(Object instance, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Class<?> klass, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Object... arguments)throws Exception
public static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Class<?>[] argumentTypes, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Object instance, String methodToExecute, Class<?> definedIn, Class<?>[] argumentTypes, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Object instance, Class<?> declaringClass, String methodToExecute, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute, Class<?>[] parameterTypes, Object... arguments) throws Exception
public static synchronized <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments) throws Exception

Following snippet is used to call the method ‘isStringPalindrome’ and pass the argument ‘madam’ to the method.

boolean isPalindrome = Whitebox.invokeMethod(util, "isStringPalindrome", "madam");

Find the following working application.

StringUtil.java
package com.sample.util;

public class StringUtil {

 /**
  * 
  * @param str
  * @return true if the string is palindrome, else false.
  */
 private boolean isStringPalindrome(String str) {
  if (str == null || str.isEmpty()) {
   return true;
  }

  return str.equals(new StringBuilder(str).reverse().toString());
 }

}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.*;

import org.junit.Test;
import org.powermock.reflect.Whitebox;

public class StringUtilTest {
 private StringUtil util = new StringUtil();

 @Test
 public void isStringPalindrome_palindrome_true() throws Exception{
  boolean isPalindrome = Whitebox.invokeMethod(util, "isStringPalindrome", "madam");
  assertTrue(isPalindrome);
 }
 
 @Test
 public void isStringPalindrome_palindrome_false() throws Exception{
  boolean isPalindrome = Whitebox.invokeMethod(util, "isStringPalindrome", "Hello");
  assertFalse(isPalindrome);
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment