当尝试块方法失败时,不会执行 catch 块



我写了一个尝试捕获块来执行测试,如果失败,则在捕获块中截取屏幕截图。但是 catch 块不会执行,当 try 块中的方法失败时,将执行 @After 方法。请参阅下面的代码。

我无法理解我在这里出了什么问题。

@Test
public void testScenarios(){
try {
test();
}catch (Exception e){
log.error(e.getLocalizedMessage(), e);
log.info("Capturing the screenshot for the failed test.");
takeScreenshot();
}
}
public void test() {
MyAccountPage myAccountPage = initElements(driver(), MyAccountPage.class);
myAccountPage.clickOrderHistoryAndDetails();
OrderHistoryPage orderHistoryPage = initElements(driver(), OrderHistoryPage.class);
orderHistoryPage.selectLatestOrder();
orderHistoryPage.verifyProduct(colour);
}

我的测试将在 orderHistoryPage.verifyProduct(color( 中失败;由于无法找到元素。

"test" 方法不会引发任何异常。

//Exception is generic, you can throw your own Exception subclass
public void test() throws Exception{
if(OK){
//Good code
}else{
//Launch your exception. Es.
throw new Exception();
}
} 

显然,您可以选择自己喜欢的执行逻辑,这只是一个例子。

在您的情况下,方法"verifyProduct"而不是捕获错误,应将其抛给调用方。

我不知道"验证产品"是如何工作的,但它可能是这样的:

if(!orderHistoryPage.verifyProduct(colour)){
throw new Exception();
}

但这仅在验证产品未找到元素时返回布尔值的情况下(Es. 1 表示成功,0 表示错误(

有关更多信息,请查看此页面

我发现了我的错误并纠正了它。首先秋天,控制根本不会尝试。因此修复了该问题,现在每当 try 块失败并相应地捕获屏幕截图时,都会执行 catch 块。谢谢你们的帮助。

最新更新