Wednesday 26 July 2017

Whitebox: Get instance of a class, without invoking its constructor

Whitebox class provides 'newInstance' method to get the instance of a class without invoking its constructor. This method is very useful, when you class contains all the private constructors and you want to instantiate for testing.

Following snippet is used to get the object of the class 'StringUtil', without invoking its constructor.
StringUtil stringUtil = (StringUtil) Whitebox.newInstance(StringUtil.class);

Find the following working application.

StringUtil.java
package com.sample.util;

public class StringUtil {

 private StringUtil() {
   System.out.println("Hello");
 }

 /**
  * 
  * @param str
  * @return true if the string is palindrome, else false.
  */
 public 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.assertFalse;
import static org.junit.Assert.assertTrue;

import java.lang.reflect.InvocationTargetException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void isStringPalindrome_empty_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

  StringUtil stringUtil = (StringUtil) Whitebox.newInstance(StringUtil.class);
  boolean isPalindrome = stringUtil.isStringPalindrome("");

  assertTrue(isPalindrome);

 }

 @Test
 public void isStringPalindrome_Palindrome_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

  StringUtil stringUtil = (StringUtil) Whitebox.newInstance(StringUtil.class);
  boolean isPalindrome = stringUtil.isStringPalindrome("madam");
  assertTrue(isPalindrome);

 }

 @Test
 public void isStringPalindrome_NotAPalindrome_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  StringUtil stringUtil = (StringUtil) Whitebox.newInstance(StringUtil.class);
  boolean isPalindrome = stringUtil.isStringPalindrome("madama");

  assertFalse(isPalindrome);

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment