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

Whitebox: test private static methods

In my previous post, I explained how to test instance private methods of a class using Whitebox class. In this post, I am going to explain how to test the static private methods using Whitebox class.

Whitebox class provides 'getMethod', by using this we can get access to a method reference of the class. Following is the signatures of overloaded forms of 'getMethod'.

public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes)
public static Method getMethod(Class<?> type, Class<?>... parameterTypes)
type : The type of the class where the method is located. If you pass any object as an argument, it will be ignored in case of static methods.
methodName : The method name to get the reference
parameterTypes : All parameter types of the method, can be null if no parameters exist.

For example, following snippet is used to test the static method 'isStringPalindrome'.

Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);
boolean isPalindrome = (Boolean) method.invoke(null, "");
assertTrue(isPalindrome);

Following is the complete 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());
 }

 public boolean isValidPassword(String password) {
  if (password == null || password.isEmpty()) {
   return false;
  }

  if (password.length() < 8) {
   return false;
  }

  if (isStringPalindrome(password)) {
   return false;
  }

  return true;
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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 {

  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(null, "");

  assertTrue(isPalindrome);

 }

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

  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(null, "madam");

  assertTrue(isPalindrome);

 }

 @Test
 public void isStringPalindrome_NotAPalindrome_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(null, "madama");

  assertFalse(isPalindrome);

 }
}




Previous                                                 Next                                                 Home

Whitebox: test private instance methods

Whitebox class provides 'getMethod', by using this we can get access to a method reference of the class. Following is the signatures of overloaded forms of 'getMethod'.

public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes)
public static Method getMethod(Class<?> type, Class<?>... parameterTypes)
type : The type of the class where the method is located.
methodName : The method name to get the reference
parameterTypes : All parameter types of the method, can be null if no parameters exist.

For example, following snippet is used to call the private method 'isStringPalindrome' of the class Whitebox.

StringUtil stringUtil = new StringUtil();
Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);
boolean isPalindrome = (Boolean) method.invoke(stringUtil, "madam");

Find the following complete 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());
 }

 public boolean isValidPassword(String password) {
  if (password == null || password.isEmpty()) {
   return false;
  }

  if (password.length() < 8) {
   return false;
  }

  if (isStringPalindrome(password)) {
   return false;
  }

  return true;
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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 = new StringUtil();

  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(stringUtil, "");

  assertTrue(isPalindrome);

 }
 
 @Test
 public void isStringPalindrome_Palindrome_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  StringUtil stringUtil = new StringUtil();

  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(stringUtil, "madam");

  assertTrue(isPalindrome);

 }
 
 @Test
 public void isStringPalindrome_NotAPalindrome_true()
   throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  StringUtil stringUtil = new StringUtil();

  Method method = Whitebox.getMethod(StringUtil.class, "isStringPalindrome", String.class);

  boolean isPalindrome = (Boolean) method.invoke(stringUtil, "madama");

  assertFalse(isPalindrome);

 }
}




Previous                                                 Next                                                 Home

Tuesday, 25 July 2017

Whitebox: get all the fields of a class

Whitebox class provides 'getFields' method to get all the fields of a class.

Following statement return te field references for the properties "noOfObjects", "name", "version".
Field[] fields = Whitebox.getFields(Model.class, "noOfObjects", "name", "version");

Following is the complete working application.

Model.java
package com.sample.model;

public class Model {

 private static int noOfObjects = 0;

 private String name = "";
 private String version = "";

 public Model() {
  this("Sample App", "1.0");
 }

 public Model(String name) {

  this(name, "1.0");

 }

 public Model(String name, String version) {
  noOfObjects++;
  this.name = name;
  this.version = version;
 }
}


ModelTest.java
package com.sample.model;

import java.lang.reflect.Field;

import org.powermock.reflect.Whitebox;

public class ModelTest {

 private static void printObjectInfo(Model model, Field[] fields)
   throws IllegalArgumentException, IllegalAccessException {
  System.out.println("*******************************");
  for (Field field : fields) {
   String name = field.getName();

   if ("noOfObjects".equals(name)) {
    System.out.println("noOfObjects :  " + field.getInt(model));
   } else if ("name".equals(name)) {
    System.out.println("name :  " + field.get(model));
   } else if ("version".equals(name)) {
    System.out.println("version :  " + field.get(model));
   }
  }
 }

 public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException {
  Field[] fields = Whitebox.getFields(Model.class, "noOfObjects", "name", "version");

  Model model1 = new Model();
  System.out.println("After crating model object1");
  printObjectInfo(model1, fields);

  System.out.println("\nAfter crating model object2");
  Model model2 = new Model("4-Factor Auth");
  printObjectInfo(model2, fields);

  System.out.println("\nAfter crating model object3");
  Model model3 = new Model("Self-Learn", "1.4");
  printObjectInfo(model3, fields);

 }
}




Previous                                                 Next                                                 Home

WhiteBox : Test private instance fields of a class

In my previous post, I explained how to access and test the private static fields using Whitebox class. In this post, I am going to explain how to access private instance field of a class.

Following snippet is used to get the value of variable 'counter' ob the object 'fibonaaci'.

Fibonaaci fibonaaci = new Fibonaaci();
Field field = Whitebox.getField(Fibonaaci.class, "counter");
long counter = field.getInt(fibonaaci);

Following is the complete working application.

Fibonaaci.java
package com.sample.service;

public class Fibonaaci {
 private int counter = 0;

 public int fib(int number) {
  counter++;
  if (number == 0 || number == 1) {
   return 1;
  }
  return fib(number - 1) + fib(number - 2);
 }
}

FibonaaciTest.java
package com.sample.service;

import static org.junit.Assert.*;

import java.lang.reflect.Field;

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

public class FibonaaciTest {

 @Test
 public void fibTest() throws IllegalArgumentException, IllegalAccessException {
  Fibonaaci fibonaaci = new Fibonaaci();

  Field field = Whitebox.getField(Fibonaaci.class, "counter");

  long counter = field.getInt(fibonaaci);
  assertEquals(counter, 0);

  field.setAccessible(true);
  field.setInt(fibonaaci, 0);
  fibonaaci.fib(2);
  counter = field.getInt(fibonaaci);
  assertEquals(counter, 3);

  field.setAccessible(true);
  field.setInt(fibonaaci, 0);
  fibonaaci.fib(3);
  counter = field.getInt(fibonaaci);
  assertEquals(counter, 5);

 }
}




Previous                                                 Next                                                 Home

Monday, 24 July 2017

WhiteBox : Test private static fields of a class

Whitebox class provide 'getField' method to access the field of a class. By using this, we can test private fields.

Following snippet access the private static field 'counter'.

Field field = Whitebox.getField(Factorial.class, "counter");
long counter = field.getLong(null);
assertEquals(counter, 0);

Find the following complete working application.

Factorial.java
package com.sample.service;

public class Factorial {
 private static int counter = 0;

 public static int factorial(int number) {
  counter++;
  if (number < 0) {
   throw new IllegalArgumentException("number should not be negative");
  }

  int result = 1;

  for (int i = 2; i <= number; i++) {
   result = result * i;
  }

  return result;
 }
}


FactorialTest.java
package com.sample.service;

import static org.junit.Assert.*;

import java.lang.reflect.Field;

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

public class FactorialTest {

 @Test
 public void test_counter() throws IllegalArgumentException, IllegalAccessException{
  Field field = Whitebox.getField(Factorial.class, "counter");
  
  long counter = field.getLong(null);
  assertEquals(counter, 0);
  
  Factorial.factorial(5);
  counter = field.getLong(null);
  assertEquals(counter, 1);
  
  Factorial.factorial(10);
  counter = field.getLong(null);
  assertEquals(counter, 2);
  

 }
}




Previous                                                 Next                                                 Home

Working with Whitebox class

WhiteBox is a simplified reflection utility class used to access various internals of a class.


You can perform following actions by using WhiteBox class.


Previous                                                 Next                                                 Home