Wednesday, 26 July 2017

Whitebox: initialize static properties

In my previous post, I explained how to set the instance properties of an object. In this post, I am going to explain how to set the static properties of a class using Whitebox.

Following snippet is used to set the static property 'count' of class Employee.
Whitebox.setInternalState(Employee.class, "count", 1123);

Find the following working application.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private static int count = 0;

 public Employee() {
  
 }

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public static int getCount() {
  return count;
 }

}


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

  Whitebox.setInternalState(Employee.class, "count", 1);
  assertEquals(Employee.getCount(), 1);
  
  Whitebox.setInternalState(Employee.class, "count", 1123);
  assertEquals(Employee.getCount(), 1123);
 }

}




Previous                                                 Next                                                 Home

No comments:

Post a Comment