본문 바로가기

공부 기록/Java

[Java] throw Exception 테스트하기

실행 환경(build.gradle)

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
    testImplementation 'org.assertj:assertj-core:3.24.2'
}

spring-boot-starter-test가 있다면 바로 jUnit5를 사용할 수 있다.

Exception을 throw하는 메서드 생성

public class MyArrayList<T> implements List<T> {

    ...
    
    public T get(int index) {
        if(index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return array[index];
    }

위와 같이 MyArrayList의 get() 메서드는 Index가 올바르지 않을 때 IndexOutOfBoundsException을 throw한다.

Exception을 throw하는 메서드 테스트

public class MyArrayListTest {

    private MyArrayList<Integer> myList;

    @BeforeEach
    public void setUp() throws Exception {
        myList = new MyArrayList<>();
        myList.add(1);
        myList.add(2);
        myList.add(3);
    }
    
    @Test
    public void getException() {
        assertThatThrownBy(() -> myList.get(-1)).isInstanceOf(IndexOutOfBoundsException.class);
        assertThatThrownBy(() -> myList.get(5)).isInstanceOf(IndexOutOfBoundsException.class);
    }
    
    ...
    
}

setUp()에서 기본적으로 myList에 1, 2, 3 요소를 추가하였으므로 get()이 가능한 index는 0부터 2까지다.

getException() 메서드 테스트에서는 get() 이 가능한 범위를 넘어서는 index로 테스트를 진행한다.

두 경우 모두 IndexOutOfBoundsException를 throw하므로 테스트는 통과한다.

'공부 기록 > Java' 카테고리의 다른 글

[Java] 큐(Queue)  (0) 2023.05.12
[Java] 문자열(String), 숫자(int, double, float, long, short) 형변환  (0) 2023.05.04
[Java] POJO  (0) 2023.05.04
[Java] LinkedList - List, Deque의 구현  (0) 2023.05.04
[Java] ObjectMapper  (0) 2023.04.28