【问题标题】:Can junit test that a method will throw an exception?junit 可以测试一个方法是否会抛出异常?
【发布时间】:2014-11-04 14:52:40
【问题描述】:

能否告诉我,编写一个抛出异常的方法(例如: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),但我必须声明该异常。

【问题讨论】:

  • 是的,这就是你要走的路。 JUnit runner 也会捕获任何抛出的异常,然后测试就会失败。
  • @Test(Expected=SomethingDoesn'tWorkException) 你可以用它来捕捉 JUnit 测试中的异常
  • @hagubear 您只想在预期异常的特定测试用例中使用expected。但在显示的示例中,throws 是必需的,但不会出现异常。
  • @Joe 对我来说似乎不是重复的。

标签: java exception junit


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    如果您调用的方法抛出了一个已检查的异常,是的,您将需要 try catch 或重新抛出。从测试本身做这个很好。有多种方法可以使用 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");
        }
    
    }
    

    【讨论】:

    • 感谢使用 ExpectedException 规则的示例。
    【解决方案3】:

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

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

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

    在这种情况下,被测试的方法应该抛出异常,所以测试会通过。如果从注解中删除expected = Exception.class,如果发生异常,测试将失败。

    【讨论】:

      【解决方案4】:

      你可以用这个来测试异常是否启动:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        相关资源
        最近更新 更多