import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.powermock.api.mockito.PowerMockito; import org.powermock.reflect.Whitebox; /** * The class that holds all unit tests for * the Employee class. * @author Deep Shah */ public class EmployeeTest { @Test() public void shouldNotDoAnythingIfEmployeeWasSaved() { Employee employee = PowerMockito.mock(Employee.class); PowerMockito.doNothing().when(employee).save(); try { employee.save(); } catch(Exception e) { Assert.fail("Should not have thrown an exception"); } } @Test(expected = IllegalStateException.class) public void shouldThrowAnExceptionIfEmployeeWasNotSaved() { Employee employee = PowerMockito.mock(Employee.class); PowerMockito.doThrow(new IllegalStateException()).when(employee).save(); employee.save(); } @Test public void shouldVerifyThatNewEmployeeIsAddedToTheDepartment() { final Department department = new Department(); final Employee employee = new Employee(); //Adding the employee to the department. department.addEmployee(employee); //Getting the privately held employees list //from the Department instance. final List employees = Whitebox.getInternalState(department, "employees"); //Asserting that the employee was added to the //list. Assert.assertTrue(employees.contains(employee)); } @Test public void shouldAddNewEmployeeToTheDepartment() { final Department department = new Department(); final Employee employee = new Employee(); final ArrayList employees = new ArrayList(); //Setting the privately held employees list with // our test employees list. Whitebox.setInternalState(department, "employees", employees); //Adding the employee. department.addEmployee(employee); //Since we substituted the privately held employees //within the department instance //we can simply assert whether our list has the // newly added employee or not. Assert.assertTrue(employees.contains(employee)); } @Test public void shouldVerifyThatMaxSalaryOfferedForADepartmentIsCalculatedCorrectly() throws Exception { final Department department = new Department(); final Employee employee1 = new Employee(); final Employee employee2 = new Employee(); employee1.setSalary(60000); employee2.setSalary(65000); //Adding two employees to the test employees list. final ArrayList employees = new ArrayList(); employees.add(employee1); employees.add(employee2); //Substituting the privately held employees list // with our test list. Whitebox.setInternalState(department, "employees", employees); //Getting the value of maxSalary from the private // field. ArrayList emps = Whitebox.getInternalState(department, "employees"); for (Employee emp : emps) { System.out.println(emp.getSalary()); } Whitebox.invokeMethod(department, "updateMaxSalaryOffered"); final long maxSalary = Whitebox.getInternalState(department, "maxSalaryOffered"); Assert.assertEquals(65000, maxSalary); } }