2015년 11월 30일 월요일

Doing exception test in Junit4

I introduce how to do test whether exception is occured correctly.

Test Target Class :

import org.springframework.web.client.ResourceAccessException;

public class TestUtil {

    public static String testMethod(String value) {
        switch (value) {
        case "success":
            return value;
        default:
            throw new ResourceAccessException("it's test");
        }
    }
}

@Test(expected = ResourceAccessException.class)
 public void testFail() {
     String success = "fail";
     TestUtil.testMethod(success);
 }

When you want to do test whether specific exception is occured,
you can do the test as above.

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() {

    expectedException.expect(ResourceAccessException.class);
    expectedException.expectMessage("it's test");

    String success = "fail";
    String ret = TestUtil.testMethod(success);

When you want to check whether some message is included in exception,
you can declare the rule, and check as above.


original source : http://blog.outsider.ne.kr/659

댓글 없음 :

댓글 쓰기