Java junit 可以测试一个方法是否会抛出异常吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26738169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:12:30  来源:igfitidea点击:

Can junit test that a method will throw an exception?

javaexceptionjunit

提问by Edison Miranda

Could you tell me please, is it normal practice to write a method (example: JUnit Test) that throws an Exception, for example:

请您告诉我,编写抛出异常的方法(例如: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);
}

In fact, method f()won't throw an exception for that parameter(5) but nevertheless I must declare that exception.

事实上,methodf()不会为该参数抛出异常(5),但我必须声明该异常。

回答by M Anouti

Yes it is completely fine, and if it does throw the exception the test will be considered as failed.

是的,完全没问题,如果确实抛出异常,则测试将被视为失败。

You need to specify that the method throws an Exceptioneven if you know that the specific case does not (this check is done by the compiler).

您需要指定该方法抛出 anException即使您知道特定情况不会(此检查由编译器完成)。

In this case, what you expect is object.f(5)returns an empty string. Any other outcome (non-empty string or throwing an exception) would result in a failed test case.

在这种情况下,您期望的是object.f(5)返回一个空字符串。任何其他结果(非空字符串或抛出异常)都会导致测试用例失败。

回答by Robert Bain

If the method you're calling throws a checked exception yes, you'll either need a try catch or to rethrow. It's fine to do this from the test itself. There are a variety of ways to test Exception using JUnit. I've tried to provide a brief summary below:

如果您正在调用的方法抛出一个检查异常,是的,您将需要一个 try catch 或重新抛出。从测试本身就可以做到这一点。有多种方法可以使用 JUnit 测试 Exception。我试图在下面提供一个简短的摘要:

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");
    }

}

回答by jjlema

You can test that the exception is launched with this:

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

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

回答by WeSt

A JUnit-Test is meant to test a given method for correct behavior. It is a perfectly valid scenario that the tested method throws an error (e.g. on wrong parameters). If it is a checked exception, you either have to add it to your test method declaration or catch it in the method and Assert to false (if the exception should not occur).

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

You can use the expectedfield in the @Testannotation, to tell JUnit that this test should pass if the exception occurs.

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

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

In this case, the tested method should throw an exception, so the test will pass. If you remove the expected = Exception.classfrom the annotation, the test will fail if an exception occurs.

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