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

Rat*_*ass 3 java junit exception-handling

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

dan*_*uch 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更多关于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?");
        }
 }
Run Code Online (Sandbox Code Playgroud)


RNJ*_*RNJ 5

我知道的两个选项.

如果使用junit4

@Test(expected = Exception.class)
Run Code Online (Sandbox Code Playgroud)

或者如果使用junit3

try {
    methodThatThrows();
    fail("this method should throw excpetion Exception");
catch (Exception expect){}
Run Code Online (Sandbox Code Playgroud)

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