背景
在构建关键字驱动测试框架的时候,明明已经在在方法try/catch并且抛出了自定义异常,但是测试报告中打印错误信息时却是InvocationTargetException。原因是:如果方法中直接抛出异常,通过反射进行调用时,会抛出InvocationTargetException异常
问题场景
- 自定义的某个关键字方法:(此例中属于KeyWordsActions类)
public static void verifyTitle(String text) throws Exception {
try {
/*自定义代码*/
}catch (Exception e){
throw new Exception("My Exception");
}
- 调用
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是测试数据
Log.info("Pass");
}catch(Exception e){
Log.error("Failed");
e.printStackTrace();
}
break;
}
}
}
- 错误日志
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是测试数据
Log.info("Pass");
}catch(Exception e){
Log.error("Failed");
System.out.println(e.getCause().toString());
}
break;
}
}
}
此时打印的信息就是自定义异常的文本