我有一个ITestListener来记录测试结果。在我的定位器类中,如果我尝试处理catch语句中的某些内容,则catch内的任何代码都不会执行。例如:我正在尝试处理可能会抛出异常的WebElement。当它引发异常时,我应该在catch语句中处理并找到其他元素。由于未执行catch语句,并且发生异常时,应用程序仅停止。即使在TestNG的onTestFailure方法为ON时,有没有办法运行catch语句?请提出解决方案。
//Test Script
public boolean loginVerification(String username, String password) {
try {
utilities.click(helloSignInLink, "elementToBeClickable");
reportLog("debug","info","Clicked on SignIn link");
utilities.sendText(loginID, username);
reportLog("debug","info","Username entered");
utilities.sendText(passwordID, password);
reportLog("debug","info","Password entered");
utilities.click(submit, "elementToBeClickable");
reportLog("debug","info","Clicked on submit button");
Thread.sleep(2000);
isTrue = driver.getTitle().contains("Vectors");
}
catch(Exception e) {
reportLog("debug","info","Unable to login with username : "+username+" , error message : "+e);
isTrue = false;
}
return isTrue;
}
我建议抓住Throwable
-不仅是Exception
。另一件事是,当您捕获到某些东西时,例外情况并没有真正出现在堆栈中,因此TestNG将永远不会知道您的测试中是否出现任何错误,并且测试侦听器不会检测到失败。解决异常后,有一种方法可以进一步推动异常。喜欢:
catch(Throwable e) {
reportLog("debug","info","Unable to login with username : "+username+" , error message : "+e);
isTrue = false;
throw e;
}
您能纠正您的方法并让我们知道问题是否仍然存在吗?
P.S。-我也看不到您的代码中的任何断言。声明结果或异常定义测试结果。
这意味着您没有捕获相同的错误捕获块。
都使用与TimeoutException
相同的例外,因此只有在发生TimeoutException
时此块才会出现。如果不确定错误,则使用通用异常块,例如Exception
,如果发生任何错误,它将确定要执行。在这种情况下,Exception
不会仅因为您已经指定了TimeoutException
而执行
try {
System.out.println("Your code");
}catch(TimeoutException t) {
System.out.println(t.getMessage());
}catch(Exception ex) {
ex.getStackTrace();
}