例如,以下代码应该捕获异常:
window == correct
testNg == wrong
为什么会发生这种情况?
我的代码:
public void scrollToElementByLocator() {
try {
driver.findElement(By.id("wrong locator")).click();
} catch (Exception e) {
System.out.println("Exception! - unable to scroll to element, Exception: " + e.toString());
}
}
答案 0 :(得分:1)
TestNG marks a test as Fail, if the code inside the test raises any Exception.
在你的代码中,当你通过捕获它自己处理异常时,不会向调用者引发异常,因此,TestNG
永远不会知道在代码中引发异常。
删除try-catch
阻止,因此会从测试中引发异常,因此TestNG
可以将测试标记为Fail
。
尝试以下代码:
@Test
public void scrollToElementByLocator() {
driver.findElement(By.id("wrong locator")).click();
}
注意:您必须使用@Test
注释标记方法,告诉TestNG
它是一种测试方法。
如果要在引发异常时执行某些操作,请尝试以下代码(抛出使用throw
关键字捕获的异常):
@Test
public void scrollToElementByLocator() {
try {
driver.findElement(By.id("wrong locator")).click();
} catch (Exception e) {
System.out.println("Exception! - unable to scroll to element, Exception: " + e.toString()); //prints the exception
throw e;
}
}