Java junit能否测试方法是否会引发异常?

Java junit能否测试方法是否会引发异常?,java,exception,junit,Java,Exception,Junit,请告诉我,编写抛出异常的方法(例如:JUnit Test)是正常做法吗,例如: class A { public String f(int param) throws Exception { if (param == 100500) throw new Exception(); return ""; } } private A object = new A(); @Test public void testSomethi

请告诉我,编写抛出异常的方法(例如:JUnit Test)是正常做法吗,例如:

class A {
    public String f(int param) throws Exception {
        if (param == 100500)
            throw new Exception();
        return "";
    }
}

private A object = new A();

@Test
public void testSomething() throws Exception {
    String expected = "";
    assertEquals(object.f(5), expected);
}

实际上,方法
f()
不会为该参数(5)引发异常,但我必须声明该异常

是的,它完全正常,如果它确实抛出异常,则测试将被视为失败

您需要指定该方法抛出一个
异常
,即使您知道特定的情况没有(此检查由编译器完成)


在本例中,您期望的是
object.f(5)
返回一个空字符串。任何其他结果(非空字符串或引发异常)都将导致测试用例失败。

如果您调用的方法引发已检查的异常,则您需要重试或重试。从测试本身就可以做到这一点。使用JUnit测试异常有多种方法。我试图在下面提供一个简短的总结:

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

/**
 * Example uses Kent Beck - Test Driven Development style test naming
 * conventions
 */
public class StackOverflowExample {

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

    @Test
    // Note the checked exception makes us re-throw or try / catch (we're
    // re-throwing in this case)
    public void calling_a_method_which_throws_a_checked_exception_which_wont_be_thrown() throws Exception {
        throwCheckedException(false);
    }

    /*
     * Put the class of the specific Exception you're looking to trigger in the
     * annotation below. Note the test would fail if it weren't for the expected
     * annotation.
     */
    @Test(expected = Exception.class)
    public void calling_a_method_which_throws_a_checked_exception_which_will_be_thrown_and_asserting_the_type()
            throws Exception {
        throwCheckedException(true);
    }

    /*
     * Using ExpectedException we can also test for the message. This is my
     * preferred method.
     */
    @Test
    public void calling_a_method_which_throws_a_checked_exception_which_will_be_thrown_and_asserting_the_type_and_message()
            throws Exception {
        expectedException.expect(Exception.class);
        expectedException.expectMessage("Stack overflow example: checkedExceptionThrower");
        throwCheckedException(true);
    }

    // Note we don't need to rethrow, or try / catch as the Exception is
    // unchecked.
    @Test
    public void calling_a_method_which_throws_an_unchecked_exception() {
        expectedException.expect(Exception.class);
        expectedException.expectMessage("Stack overflow example: uncheckedExceptionThrower");
        throwUncheckedException();
    }

    private void throwCheckedException(boolean willThrow) throws Exception {
        // Exception is a checked Exception
        if (willThrow) {
            throw new Exception("Stack overflow example: checkedExceptionThrower");
        }
    }

    private void throwUncheckedException() throws NullPointerException {
        // NullPointerException is an unchecked Exception
        throw new NullPointerException("Stack overflow example: uncheckedExceptionThrower");
    }

}

您可以通过以下方式测试是否启动了异常:

@Test(expected = ValidationException.class)
public void testGreaterEqual() throws ValidationException {
    Validate.greaterEqual(new Float(-5), 0f, "error7");
}

JUnit测试旨在测试给定方法的正确行为。测试方法抛出错误(例如错误的参数)是一个非常有效的场景。如果它是一个已检查的异常,则必须将其添加到测试方法声明中,或者在方法中捕获它并断言为false(如果该异常不应发生)

您可以使用
@Test
注释中的
expected
字段,告诉JUnit如果发生异常,该测试应该通过

@Test(expected = Exception.class)
public void testSomething() throws Exception {
    String expected = "";
    assertEquals(object.f(5), expected);
}

在这种情况下,被测试的方法应该抛出一个异常,因此测试将通过。如果从注释中删除
expected=Exception.class
,则如果出现异常,测试将失败。

是的,这就是您的方法。JUnit运行程序还将捕获任何抛出的异常,然后测试将失败。@test(Expected=somethingdots'tWorkException)您可以使用它捕获JUnit中的异常test@hagubear您只希望在预期出现异常的特定测试用例中使用
expected
。但是在所示的示例中,需要
抛出
,但不需要异常。对我来说,@Joe的可能重复项似乎不是重复项。感谢使用ExpectedException规则的示例。
@Test(expected = Exception.class)
public void testSomething() throws Exception {
    String expected = "";
    assertEquals(object.f(5), expected);
}