단위 테스트를 하기 위해 모든 메서드를 public으로 접근하도록 했다. 하지만 그렇게 되면 캡슐화부터 다른 클래스에서 메서드를 접근하여 값을 변경하는 등 많은 문제가 발생한다. 그래서 private를 사용했는데 그럼 이부분은 어떻게 테스트해야하는지에 대한 의문을 가지고 해당 내용을 찾게 되었다.
1) Result의 객체
public class Result {
private int add(int a, int b){
return a+b;
}
}
2) Result의 add 테스트코드로 접근하기
class ResultTest {
@Test
public void 더하기_구하기(){
// 1. private 클래스 생성
Result result = new Result();
// 2. private 메서드를 호출하기 위해 Method클래스 생성
Method method = Result.getClass().getDeclaredMethod("add", int.class, int.class);
// 3. private 메서드 접근 허용가능하도록
method.setAccessible(true);
// 4. 메서드 실행(반환값 변환)
int sum = (int) method.invoke(result, 1,2);
// 5. 결과값 비교
Assertions.assertThat(sum).isEqualTo(3);
}
}
private 메서드를 가지고 있는 클래스를 생성해준다. [Result winner = new Result();]
private 메서드를 호출하기 위해 Method 클래스를 만들어준다.
(Private 메서드 가지는 클래스).getClass().getDeclaredMethod("메서드명", 파라미터(원시 타입), 파라미터(원시 타입));
private 메서드를 Method 객체에 담아 접근 허용가능하도록 만들어준다.
invoke를 통해 메서드를 실행
결과값 비교
1) winner 객체
public class Winner {
private int maxDistance(List<Car> cars){
int max = 0;
for (Car car : cars) {
max = Math.max(car.getPosition(),max);
}
return max;
}
}
2) winnerTest시 파라미터 주의
class WinnerTest {
@Test
public void 최대_이동거리_구하기() throws Exception{
// 1. private 클래스 생성
Winner winner = new Winner()
// 2. private 메서드를 호출하기 위해 Method클래스 생성(파라미터값 주의)
Method method = winner.getClass().getDeclaredMethod("maxDistance", List.class);
// 3. private 메서드 접근 허용가능하도록
method.setAccessible(true);
// 4. 메서드 실행(반환값 변환)
int result = (int) method.invoke(winner, cars);
}
}
1)Number클래스
public class JNumber {
private int count = 100;
}
2)NumberTest클래스
public class NumberTest {
@Test
public void test(){
// 1. private 클래스 생성
Number number = new Number();
// 2. private 변수를 호출하기 위해 Field클래스 생성
Field field = jUnitTestClass.getClass().getDeclaredField("count");
// 3. private 메서드 접근 허용가능하도록
field.setAccessible(true);
// 4. 메서드 실행(반환값 변환)
int value = (int)field.get(number);
// 5. 결과반환
assertThat(value, is(100));
}
}