반응형
ReflectionTestUtils를 이용하여 private field or method 를 테스트 할 수 있다.
public class Student {
private int id;
private String getFirstNameAndId(){
return getFirstName() + " " + getId();
}
}
@SpringBootTest
class StudentTest {
@Autowired
Student student;
@BeforeEach
void studentBeforeEach(){
student.setFirstName("Eric");
student.setLastName("Roby");
student.setEmailAddress("asdfa@asdf.com");
student.setStudentGrades(studentGrades);
ReflectionTestUtils.setField(student,"id", 1);
ReflectionTestUtils.setField(student, "studentGrades", new ArrayList<>(Arrays.asList(100.0,95.0,85.5,40,5)));
}
@Test
void privateFieldTest() {
Student student =(Student)context.getBean("student");
assertEquals(1,ReflectionTestUtils.getField(student, "id",1));
}
@Test
void privateMethodTest() {
Student student =(Student)context.getBean("student");
assertEquals("Eric",ReflectionTestUtils.invokeMethod(student, "getFirstNameAndId"));
}
}
반응형
'SpringBoot' 카테고리의 다른 글
자바의 Supplier와 Consumer 인터페이스 이해와 활용 (0) | 2023.10.09 |
---|---|
Spring Boot Config Server (0) | 2023.09.29 |
Spring boot Throwing Exception test (0) | 2022.05.22 |
Spring boot @MockBean (0) | 2022.05.22 |
Spring boot Mockito Example - @Mock & @InjectMocks (0) | 2022.05.22 |