如何使用JUnit进行单元测试时处理异常?

时间:2012-08-29 18:28:32

标签: java exception-handling junit

如果一个方法抛出异常,如何编写一个测试用例来验证该方法是否实际抛出了预期的异常?

3 个答案:

答案 0 :(得分:12)

在最新版本的JUnit中,它以这种方式工作:

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class NumberFormatterExceptionsTests {

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

    @Test
    public void shouldThrowExceptionWhenDecimalDigitsNumberIsBelowZero() {
        thrown.expect(IllegalArgumentException.class); // you declare specific exception here
        NumberFormatter.formatDoubleUsingStringBuilder(6.9, -1);
    }
}

更多关于ExpectedExceptions:

http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html

http://alexruiz.developerblogs.com/?p=1530

// These tests all pass.
 public static class HasExpectedException {
        @Rule
        public ExpectedException thrown= ExpectedException.none();

        @Test
        public void throwsNothing() {
    // no exception expected, none thrown: passes.
        }

        @Test
        public void throwsNullPointerException() {
                thrown.expect(NullPointerException.class);
                throw new NullPointerException();
        }

        @Test
        public void throwsNullPointerExceptionWithMessage() {
                thrown.expect(NullPointerException.class);
                thrown.expectMessage("happened?");
                thrown.expectMessage(startsWith("What"));
                throw new NullPointerException("What happened?");
        }
 }

答案 1 :(得分:5)

我知道的两个选项。

如果使用junit4

@Test(expected = Exception.class)

或者如果使用junit3

try {
    methodThatThrows();
    fail("this method should throw excpetion Exception");
catch (Exception expect){}

这两个捕获异常。我建议捕获您正在寻找的异常,而不是通用异常。

答案 2 :(得分:0)

您可以尝试捕获所需的异常并执行assertTrue(true)

之类的操作
@Test
testIfThrowsException(){
    try{
        funcThatShouldThrowException(arg1, agr2, agr3);
        assertTrue("Exception wasn't thrown", false);
    }
    catch(DesiredException de){
        assertTrue(true);
    }
}