Wednesday 26 July 2017

Whitebox: invoke static method

In my previous post, I explained how to invoke instance methods of an object. In this post, I am going to explain how to invoke static methods of a class.

Whitebox class provides the method 'invokeMethod', it is used to invoke the methods of 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 static method ‘isStringPalindrome’ and pass the argument ‘madam’ to the method.

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

Following is the working application.

StringUtil.java
package com.sample.util;

public class StringUtil {

 /**
  * 
  * @param str
  * @return true if the string is palindrome, else false.
  */
 private static 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 {

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




Previous                                                 Next                                                 Home

No comments:

Post a Comment