단위 테스트 작성시 Private 접근자를 가진 메소드를 테스트하는 방법을 정리합니다.
2가지 방식으로 Private 접근자를 가진 메소드를 단위테스트하는 예제입니다.
- Reflection 활용
- Spring Framework의 RelectionTestUtils
Reflection을 활용한 private static 메서드 단위 테스트
Relection으로 특정 클래스에서 테스트 할 메서드를 불러온 후 accessible 필드를 true로 설정합니다.
그리고 invoke() 메서드를 사용해 테스트 할 Private 메서드를 실행합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public class { private static boolean checkLength(String str) { if (str.length() > 10) { return false; } return true; } }
@RunWith(SpringRunner.class) @SpringBootTest public class ValidatorTest { @Autowired private Validator validator;
@Test public void testCheckLength() throws Exception { Method checkLength = Validator.class.getDeclaredMethod("checkLength", String.class); checkLength.setAccessible(true);
boolean result = (boolean)checkLength.invoke(checkLength, "abcdefghijklmn"); assertFalse(result);
result = (boolean)checkLength.invoke(checkLength, "12345"); assertTrue(result); } }
|
Spring Framework의 ReflectionTestUtils를 활용한 Private 메서드 단위 테스트
RelectionTestUtils 클래스의 Static 메서드인 invokeMethod() 메서드를 사용하여 테스트 할 Private 메서드를 실행합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class Common { private String getVersion() { return "1.0.0-RELEASE"; } }
@RunWith(SpringRunner.class) @SpringBootTest public class CommonTest { @Autowired private Common common;
@Test public void testGetVersion() throws Exception { String result = ReflectionTestUtils.invokeMethod(common, "getVersion"); assertEquals("1.0.0-RELEASE", result); } }
|
Reference
近期评论