반응형

JUnit을 이용하여 유닛 테스트를 하다 보면 예외를 테스트 해야 하는 경우가 있다.

 

아래 코드를 통해 바로 확인해보자.

 

아래 코드는 div라는 메서드를 이용하여 2 / 2를 하는데 expected는 0이었으나 실제 계산된 값은 1이므로 테스트 결과가같지 않아 fail이 나는 상태이다.

package com.example.customnotepad;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class JUnitTest {

    @Test
    public void test() {
        int ret = div(2,2);
        assertThat(0, is(ret));
    }

    private int div(int a, int b){
        return a / b;
    }
}

 

이번엔 아래 코드를 보자.

0으로 나누는 행위를 취하니 AritArithmeticException 이 발생했다.

 

이처럼 의도적으로 exception을 발생시키는 테스트를 해야하는 경우 이를 test pass로 만들기 위해서는 마지막 코드를 통해 확인해보자.

package com.example.customnotepad;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class JUnitTest {

    @Test
    public void test() {
        int ret = div(2,0);
        assertThat(0, is(ret));
    }

    private int div(int a, int b){
        return a / b;
    }
}

 

 

 

@Test(expected = ExceptionName.class) 를 통해 해당 예외는 이미 예측된 것이고 패스로 가정 할 수 있도록 만들 수 있다.

package com.example.customnotepad;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class JUnitTest {

    @Test(expected = ArithmeticException.class)
    public void test() {
        int ret = div(2,0);
        assertThat(0, is(ret));
    }

    private int div(int a, int b){
        return a / b;
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형