Junit 是 Java 编程语言的单元测试框架。如果您想阅读有关 junit 测试遵循的最佳实践,那么这里有一个很好的指南供您参考。
在这篇文章中,我正在编写一个示例测试用例,它期望在运行时抛出异常。如果它得到预期的异常,则测试通过。如果未检测到预期异常,则测试用例失败。
这些类型的测试用例在您希望您的应用程序因非常荒谬的输入而失败时非常有用。
package com.cundage.test.junit; import org.junit.Test; public class ExpectedExceptionTest { //This test case fails because it was expecting ArithmeticException @Test(expected = ArithmeticException.class) public void expectArithmeticException() { System.out.println("Everything was fine here !!"); } //This test case fails because it was expecting ArithmeticException @Test(expected = ArithmeticException.class) public void expectArithmeticException2() { throw new NullPointerException(); } //This test case passes because it was expecting NullPointerException @Test(expected = NullPointerException.class) public void expectNullPointerException() { //some code which throw NullPointerException in run time throw new NullPointerException(); } }
在上面的 3 个测试用例中,前两个失败了,因为他们期望在测试用例执行时没有得到 ArithmeticException。
第三个测试用例通过了,因为它期望 NullPointerException 并且测试用例抛出了它。
通过这种方式,您可以编写依赖于某些异常的测试用例来测试应用程序在失败时的行为。
快乐学习!!
地址:https://www.cundage.com/article/junit-testcases-which-expects-exception-on-runtime.html