Wednesday 26 July 2017

Whitebox: initialize properties of an object

Whitebox provides following methods to set the value to a field.

public static void setInternalState(Object object, String fieldName, Object value)
public static void setInternalState(Object object, String fieldName, Object[] value)
public static void setInternalState(Object object, Object value, Object... additionalValues)
public static void setInternalState(Object object, Object value, Class<?> where)
public static void setInternalState(Object object, String fieldName, Object value, Class<?> where)
public static void setInternalState(Object object, Class<?> fieldType, Object value)
public static void setInternalState(Object object, Class<?> fieldType, Object value, Class<?> where)

Following snippet define the properties of the object 'Employee'.

Employee emp = new Employee();
                
Whitebox.setInternalState(emp, "id", 1234);
Whitebox.setInternalState(emp, "firstName", "Hari Krishna");
Whitebox.setInternalState(emp, "lastName", "Gurram");

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() {

 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

}


EmployeeTest.java
package com.sample.model;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.InvocationTargetException;

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

public class EmployeeTest {

 @Test
 public void Employee_DefaultConstructor()
   throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  Employee emp = new Employee();
  
  Whitebox.setInternalState(emp, "id", 1234);
  Whitebox.setInternalState(emp, "firstName", "Hari Krishna");
  Whitebox.setInternalState(emp, "lastName", "Gurram");
  
  assertproperties(emp, 1234, "Hari Krishna", "Gurram");
 }
 
 
 private void assertproperties(Employee emp, int id, String firstName, String lastName) {

  assertEquals(emp.getId(), id);
  assertEquals(emp.getFirstName(), firstName);
  assertEquals(emp.getLastName(), lastName);

 }

}





Previous                                                 Next                                                 Home

No comments:

Post a Comment