Tuesday 25 July 2017

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

No comments:

Post a Comment