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

No comments:

Post a Comment