在这篇文章中,我们将讨论TestNG中的exceptedExceptions属性。
exceptedExceptions属性有什么作用?有时,在我们的测试用例中,我们需要验证是否发生了某些异常。这个属性将帮助我们实现这一点。它需要一个异常类数组并检查该异常是否发生。
但是,如果列出的任何异常没有发生,它将通过该测试。
语法
exceptedExceptions将采用一串异常类,如下所示-
@Test(expectedExceptions = {IOException.class, ArithmeticException.class})
现在,我们将编写三个测试用例——
- test1-这将使用预期的异常={IOExceptions. class,ArithmeticException.class}并抛出IOException,这是列出的异常的一部分。
- test2-这也将使用预期的异常={IOExceptions. class,ArithmeticException.class},但不会引发任何异常。
- test3-这也将使用预期的异常={IOExceptions. class,ArithmeticExceptions.class},但会抛出一个ArrayIndexOutOfBoundsException,这不是列出的异常的一部分
import java.io.IOException;
import org.testng.annotations.Test;public class CodekruTest {// this test will pass@Test(expectedExceptions = { IOException.class, ArithmeticException.class })public void test1() throws IOException {System.out.println("test1 throwing an IOException");throw new IOException();}// this test will fail@Test(expectedExceptions = { IOException.class, ArithmeticException.class })void publictest2() {System.out.println("test2 not throwing an exception");}// this test will also fail@Test(expectedExceptions = { IOException.class, ArithmeticException.class })void publictest3() {System.out.println("test3 throwing an ArrayIndexOutOfBoundsException");throw new ArrayIndexOutOfBoundsException();}}
输出-
test1 throwing an exception
test2 not throwing an exception
test3 throwing an exception
PASSED: test1
FAILED: test2
FAILED: test3===============================================Default testTests run: 3, Failures: 2, Skips: 0
===============================================
- test1()传递是因为抛出的异常与预期异常列表中存在的异常之一匹配。
- test2()失败,因为没有抛出异常,并且预计应该抛出列出的预期异常之一。
- test3()失败,因为抛出了不同的异常类型,未在预期的异常列表中列出。