Wednesday 26 July 2017

Whitebox: get the value of instance property

Whitebox class provides method 'getInternalState' to get the state of instance property.

public static <T> T getInternalState(Object object, String fieldName)
public static <T> T getInternalState(Object object, String fieldName, Class<?> where)
public static <T> T getInternalState(Object object, Class<T> fieldType)
public static <T> T getInternalState(Object object, Class<T> fieldType, Class<?> where)

Following snippet is used to get the values associated with properties id, firstName and lastName respectively.

int id = Whitebox.getInternalState(emp, "id");
String firstName = Whitebox.getInternalState(emp, "firstName");
String lastName = Whitebox.getInternalState(emp, "lastName");
                
Find the following working application.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public Employee(int id, String firstName, String lastName) {
  super();
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

}


EmployeeTest.java
package com.sample.model;

import static org.junit.Assert.assertEquals;

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

public class EmployeeTest {

 @Test
 public void Employee_DefaultConstructor() {

  Employee emp = new Employee(1, "Hari Krishna", "Gurram");
  
  int id = Whitebox.getInternalState(emp, "id");
  String firstName = Whitebox.getInternalState(emp, "firstName");
  String lastName = Whitebox.getInternalState(emp, "lastName");
  
  assertEquals(id, 1);
  assertEquals(firstName, "Hari Krishna");
  assertEquals(lastName, "Gurram");
  
 }

}



Previous                                                 Next                                                 Home

No comments:

Post a Comment