3

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

4

3 回答 3

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?");
        }
 }
于 2012-08-29T18:32:15.140 回答
5

我知道的两个选项。

如果使用junit4

@Test(expected = Exception.class)

或者如果使用 junit3

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

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

于 2012-08-29T18:32:47.697 回答
0

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

@Test
testIfThrowsException(){
    try{
        funcThatShouldThrowException(arg1, agr2, agr3);
        assertTrue("Exception wasn't thrown", false);
    }
    catch(DesiredException de){
        assertTrue(true);
    }
}
于 2012-08-29T18:30:14.010 回答