반응형
2가지 방식으로 Private 접근자를 가진 메소드를 단위테스트하는 예제입니다.
- Reflection 활용
- Spring Framework의 RelectionTestUtils
Reflection을 활용한 private static 메서드 단위 테스트
Relection으로 특정 클래스에서 테스트 할 메서드를 불러온 후 accessible 필드
를 true
로 설정합니다.
그리고 invoke()
메서드를 사용해 테스트 할 Private 메서드를 실행합니다.
@Component
public class Validator {
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 메서드를 실행합니다.
@Component
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
반응형
'프로그래밍 > Java & Spring Framework' 카테고리의 다른 글
스트림(Stream) 활용 (0) | 2019.11.16 |
---|---|
스트림 (Stream) (0) | 2019.11.16 |
람다 표현식 (Lambda Expression) (0) | 2019.11.16 |
동작 파라미터화 (Behavior Parameterization) (0) | 2019.11.16 |