testNG异常测试
testNG异常测试只程序本身会抛出某个异常,期望结果和抛出的异常一致,则测试通过,如果不一致则失败。
代码如下
package com.course.testng;
import org.testng.annotations.Test;
public class ExpectedException {
/**
* 什么时候会用到异常测试?
* 在我们期望结果为某个异常的时候
* 比如:我们传入了某些不合法的参数,程序抛出了异常
* 也就是期望结果结果就是这个异常
*/
/**
* 异常测试失败,抛出的异常和期望结果ArithmeticException不符
*/
@Test(expectedExceptions = ArithmeticException.class)
public void runTimeExceptionFail() {
System.out.println("这应该抛出一个RuntimeException异常");
throw new RuntimeException();
}
/**
* 异常测试成功
*/
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
int i = 1 / 0;
System.out.println("这是一个成功的异常测试");
}
}
运行结果
1 C:\Users\Administrator\.IntelliJIdea2019.3\system\temp-testng-customsuite.xml 2 3 4 这应该抛出一个RuntimeException异常 5 6 7 8 java.lang.RuntimeException 9 at com.course.testng.ExpectedException.runTimeExceptionSuccess(ExpectedException.java:19) 10 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 11 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 12 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 13 at java.lang.reflect.Method.invoke(Method.java:498) 14 at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104) 15 at org.testng.internal.Invoker.invokeMethod(Invoker.java:645) 16 at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851) 17 at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177) 18 at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129) 19 at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112) 20 at org.testng.TestRunner.privateRun(TestRunner.java:756) 21 at org.testng.TestRunner.run(TestRunner.java:610) 22 at org.testng.SuiteRunner.runTest(SuiteRunner.java:387) 23 at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382) 24 at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) 25 at org.testng.SuiteRunner.run(SuiteRunner.java:289) 26 at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) 27 at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) 28 at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293) 29 at org.testng.TestNG.runSuitesLocally(TestNG.java:1218) 30 at org.testng.TestNG.runSuites(TestNG.java:1133) 31 at org.testng.TestNG.run(TestNG.java:1104) 32 at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66) 33 at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110) 34 35 36 =============================================== 37 Default Suite 38 Total tests run: 2, Failures: 1, Skips: 0 39 =============================================== 40 41 42 Process finished with exit code 0