Java 当try block方法失败时,不会执行Catch块

Java 当try block方法失败时,不会执行Catch块,java,selenium,selenium-webdriver,junit,webdriver,Java,Selenium,Selenium Webdriver,Junit,Webdriver,我编写了一个try-catch块来执行测试,如果测试失败,则在catch块中截图。但是,当try块中的方法失败时,不会执行catch块,也会执行@After方法。请参阅下面的代码 我不明白我在这里哪里出错了 @Test public void testScenarios(){ try { test(); }catch (Exception e){ log.error(e.getLocalizedMessage(), e); log.

我编写了一个try-catch块来执行测试,如果测试失败,则在catch块中截图。但是,当try块中的方法失败时,不会执行catch块,也会执行@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中失败。验证产品(颜色);由于无法定位元素。

该“测试”方法不会引发任何异常

//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”而不是捕获错误,应该将其抛出给调用方

我不知道“verifyProduct”是如何工作的,但它可能是这样的:

if(!orderHistoryPage.verifyProduct(colour)){
   throw new Exception();
}
但这仅适用于verifyProduct未找到元素时返回布尔值的情况(Es.1表示成功,0表示错误)


有关更多信息,请查看我发现的错误并予以纠正。第一个秋天,控制组根本不打算尝试。因此,修复了这个问题,现在每当try块失败时,就会执行catch块,并相应地捕获屏幕截图。谢谢你们的帮助

您如何知道test()方法失败?如果test()引发异常,将调用catch块。将记录器放在test()方法下面的try块中,并检查它是否真的引发异常。此外,请检查test()方法中的方法。有可能他们在隐式地处理异常。什么样的失败?是否存在失败的断言或异常?当断言失败时,将抛出一个
错误
,而不是一个
异常
。我的测试将在orderHistoryPage.verifyProduct(彩色)中失败;由于无法定位元素。我想添加不正确的元素xpath。因此它失败了,但没有捕获屏幕截图。运行测试时收到的异常是org.openqa.selenium.NoSuchElementException:没有这样的元素:无法定位元素:{“方法”:“xpath”,“选择器”:“//table[@id='order-list1']/tbody/tr/td[@data value=20180920071210]/previous sibling::td[@class='history\u link bold footable first column']>(会话信息:headless chrome=68.0.3440.84)您是否将
log
设置为某个值?可能您的第一个异常之后会立即出现
NullPointerException