原文: https://howtodoinjava.com/junit/junit-testcases-which-expects-exception-on-runtime/

    Junit 是 Java 编程语言的单元测试框架。 如果您想阅读有关最佳实践的信息,以进行 junit 测试,那么这里是一份出色的指南供您参考。

    在本文中,我正在编写一个示例测试用例,期望在运行时引发异常。 如果它获得预期的异常,则测试通过。 如果未检测到预期的异常,则测试用例失败。

    如果您希望应用因非常荒谬的输入而失败,这些类型的测试用例将非常有用。

    1. package com.howtodoinjava.test.junit;
    2. import org.junit.Test;
    3. public class ExpectedExceptionTest
    4. {
    5. //This test case fails because it was expecting ArithmeticException
    6. @Test(expected = ArithmeticException.class)
    7. public void expectArithmeticException()
    8. {
    9. System.out.println("Everything was fine here !!");
    10. }
    11. //This test case fails because it was expecting ArithmeticException
    12. @Test(expected = ArithmeticException.class)
    13. public void expectArithmeticException2()
    14. {
    15. throw new NullPointerException();
    16. }
    17. //This test case passes because it was expecting NullPointerException
    18. @Test(expected = NullPointerException.class)
    19. public void expectNullPointerException()
    20. {
    21. //some code which throw NullPointerException in run time
    22. throw new NullPointerException();
    23. }
    24. }

    在上述 3 个测试用例中,前两个失败是因为他们期望ArithmeticException,而在执行测试用例时并没有得到。

    第三个测试用例获得通过,因为它期望NullPointerException并被测试用例抛出。

    这样,您可以编写依赖于某些异常的测试用例,以测试失败时应用的行为。

    祝您学习愉快!