环球科技在此|Java自动化测试框架(TestNG)——异常测试


环球科技在此|Java自动化测试框架(TestNG)——异常测试
文章图片
在使用TestNG进行测试时 , 有些场景 , 我们通过向测试方法传入某些异常的参数 , 期望代码抛出异常时 , 我们可以通过@Test(expectedExceptions,expectedExceptionsMessageRegExp)实现 , 并且可以实现异常信息的断言 。
运行时异常与检查异常
Java中对于异常分为运行时异常与检查异常 。
运行时异常 , 编译时不被检查的异常 , 不需要用throws声明抛出异常对象所属类 , 也可以不用throw抛出异常对象或异常引用 。 对于调用该方法 , 也不需要放于try-catch代码块中 。 (避免程序代码错误被掩盖在运行中无法察觉)
检查异常 , 编译时被检测的异常 , 一旦用throw抛出异常 , 如果当前方法可处理异常 , 那么需要在该方法内通过try-catch处理异常 。 如果当前方法不具备该异常的处理能力 , 那么必须在参数列表后方法体前使用throws声明异常所属类 , 交给方法的调用方处理 。
运行时异常测试(RuntimeException)
首先先创建一个自定义运行时异常类CustomRuntimeException , 如下
packagetestng.base.demo;?publicclassCustomRuntimeExceptionextendsRuntimeException{?//无参构造方法publicCustomRuntimeException(){super();}?//含参的构造方法 , 指定异常的详细信息publicCustomRuntimeException(Stringmessage){super(message);}?//含参的构造方法 , 指定异常的详细信息和原因publicCustomRuntimeException(Stringmessage,Throwablecause){super(message,cause);}?//含参的构造方法 , 指定异常的原因publicCustomRuntimeException(Throwablecause){super(cause);}?}创建一个测试类:runtimeExceptionTest.jav , 其代码如下所示-
publicclassruntimeExceptionTest{@TestpublicvoidtestExceptionDemo(){thrownewCustomException(''TestNGcustomRuntimeException.'');}?}?执行该测试用例 , 将抛出如下异常信息
testng.base.demo.CustomException:TestNGcustomRuntimeException.?attestng.base.demo.runtimeExceptionTest.testExceptionDemo(runtimeExceptionTest.java:7)atorg.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)atorg.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)atcom.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)atcom.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)【环球科技在此|Java自动化测试框架(TestNG)——异常测试】我们期望结果就是抛出该异常信息 , 但此时用例执行失败了 。 与我们想要的期望在抛出异常时 , 用例执行成功的结果不一致 , 此时我们可以在@Test注解中通过expectedExceptions参数实现 , 如下:
packagetestng.base.demo;importorg.testng.annotations.Test;?publicclassruntimeExceptionTest{@Test(expectedExceptions=CustomRuntimeException.class)publicvoidtestExceptionDemo(){thrownewCustomRuntimeException(''TestNGcustomRuntimeException.'');}?}此时 , 执行测试用例时 , 执行结果是成功的 , 如下
?===============================================DefaultSuiteTotaltestsrun:1,Failures:0,Skips:0===============================================我们还可以对抛出异常的信息进行判断 , 同样在@Test注解中通过expectedExceptionsMessageRegExp参数实现 , 如下:
packagetestng.base.demo;importorg.testng.annotations.Test;?publicclassruntimeExceptionTest{@Test(expectedExceptions=CustomRuntimeException.class,expectedExceptionsMessageRegExp=''TestNGcustomRuntimeException.'')publicvoidtestExceptionDemo(){thrownewCustomRuntimeException(''TestNGcustomRuntimeException.'');}}?当抛出的异常信息与expectedExceptionsMessageRegExp参数不一致时 , 用例将运行失败 。


推荐阅读