본문 바로가기
SpringBoot

Spring boot Private field and method Test

by ByteBridge 2022. 5. 22.
반응형
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"));
    }


}
반응형