|
| 1 | +package org.baeldung.reflectiontestutils; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | +import static org.mockito.Mockito.mock; |
| 5 | + |
| 6 | +import org.baeldung.reflectiontestutils.repository.Employee; |
| 7 | +import org.baeldung.reflectiontestutils.repository.EmployeeService; |
| 8 | +import org.baeldung.reflectiontestutils.repository.HRService; |
| 9 | +import org.junit.Test; |
| 10 | +import org.springframework.test.util.ReflectionTestUtils; |
| 11 | + |
| 12 | +import static org.mockito.Mockito.when; |
| 13 | + |
| 14 | +public class ReflectionTestUtilsUnitTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void whenNonPublicField_thenReflectionTestUtilsSetField() { |
| 18 | + Employee employee = new Employee(); |
| 19 | + ReflectionTestUtils.setField(employee, "id", 1); |
| 20 | + assertTrue(employee.getId().equals(1)); |
| 21 | + |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + public void whenNonPublicMethod_thenReflectionTestUtilsInvokeMethod() { |
| 26 | + Employee employee = new Employee(); |
| 27 | + ReflectionTestUtils.setField(employee, "id", 1); |
| 28 | + employee.setName("Smith, John"); |
| 29 | + assertTrue(ReflectionTestUtils.invokeMethod(employee, "employeeToString").equals("id: 1; name: Smith, John")); |
| 30 | + } |
| 31 | + |
| 32 | + @Test |
| 33 | + public void whenInjectingMockOfDependency_thenReflectionTestUtilsSetField() { |
| 34 | + Employee employee = new Employee(); |
| 35 | + ReflectionTestUtils.setField(employee, "id", 1); |
| 36 | + employee.setName("Smith, John"); |
| 37 | + |
| 38 | + HRService hrService = mock(HRService.class); |
| 39 | + when(hrService.getEmployeeStatus(employee.getId())).thenReturn("Active"); |
| 40 | + EmployeeService employeeService = new EmployeeService(); |
| 41 | + |
| 42 | + // Inject mock into the private field |
| 43 | + ReflectionTestUtils.setField(employeeService, "hrService", hrService); |
| 44 | + assertEquals("Employee " + employee.getId() + " status: Active", employeeService.findEmployeeStatus(employee.getId())); |
| 45 | + } |
| 46 | +} |
0 commit comments