背景
在構(gòu)建關(guān)鍵字驅(qū)動(dòng)測(cè)試框架的時(shí)候,明明已經(jīng)在在方法try/catch并且拋出了自定義異常,但是測(cè)試報(bào)告中打印錯(cuò)誤信息時(shí)卻是InvocationTargetException。原因是:如果方法中直接拋出異常,通過反射進(jìn)行調(diào)用時(shí),會(huì)拋出InvocationTargetException異常
問題場(chǎng)景
- 自定義的某個(gè)關(guān)鍵字方法:(此例中屬于KeyWordsActions類)
public static void verifyTitle(String text) throws Exception {
try {
/*自定義代碼*/
}catch (Exception e){
throw new Exception("My Exception");
}
- 調(diào)用
public static void main(String args[]) throws Exception{
KeyWords keyWords = new KeyWords();
Method[] method = keyWords.getClass().getMethods();
for(int i=0;i<method.length;i++){
if("verifyTitle".equals(method[i].getName())){
try {
method[i].invoke(keyWords,value);//value是測(cè)試數(shù)據(jù)
Log.info("Pass");
}catch(Exception e){
Log.error("Failed");
e.printStackTrace();
}
break;
}
}
}
- 錯(cuò)誤日志
java.lang.reflect.InvocationTargetException
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
Caused by: java.lang.Exception: My Exception
at com.wjn.configuration.KeyWordsActions.waitElement(KeyWordsActions.java:33)
... 30 more
解決方案
通過異常日志看到最終拋出的是java.lang.reflect.InvocationTargetException異常。Caused by自定義異常.
查看源代碼如下
**
* @exception InvocationTargetException if the underlying method throws an exception.
*/
@CallerSensitive
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
可以通過e.getCause().toString()打印出自定義日志信息
public static void main(String args[]) throws Exception{
KeyWords keyWords = new KeyWords();
Method[] method = keyWords.getClass().getMethods();
for(int i=0;i<method.length;i++){
if("verifyTitle".equals(method[i].getName())){
try {
method[i].invoke(keyWords,value);//value是測(cè)試數(shù)據(jù)
Log.info("Pass");
}catch(Exception e){
Log.error("Failed");
System.out.println(e.getCause().toString());
}
break;
}
}
}
此時(shí)打印的信息就是自定義異常的文本