【问题标题】:Catch block is not executed when try block method is failed当 try 块方法失败时,不执行 Catch 块
【发布时间】:2019-02-27 20:17:38
【问题描述】:

我写了一个 try catch 块来执行测试,如果它失败了,然后在 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(colour); 中失败由于无法定位元素。

【问题讨论】:

  • 你怎么知道 test() 方法失败了?如果 test() 抛出 Exception,则将调用 catch 块。在 test() 方法下方的 try 块中放置一个记录器,并检查它是否真的抛出 Exception。此外,检查 test() 方法中的方法。他们可能正在隐式地进行异常处理。
  • 什么样的失败?是否存在失败的断言或异常?当断言失败时,会抛出 Error,而不是 Exception
  • 我的测试将在 orderHistoryPage.verifyProduct(colour); 中失败;由于无法定位元素。我想要添加不正确的元素 xpath。所以它失败了,但没有捕获屏幕截图。
  • 运行测试时收到的异常是 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//table [@id = 'order-list1']/tbody/tr/td[@data-value = 20180920071210]/preceding-sibling::td[@class= 'history_link bold footable-first-column']"}(会话信息: 无头铬=68.0.3440.84)
  • 您是否将log 设置为某些内容?也许您的第一个异常紧随其后的是NullPointerException

标签: java selenium selenium-webdriver junit webdriver


【解决方案1】:

“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”而不是捕捉错误,应该把它扔给调用者。

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

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

但这只是在 verifyProduct 没有找到元素时返回布尔值的情况(Es. 1 表示成功,0 表示错误)

欲了解更多信息,请查看this page

【讨论】:

    【解决方案2】:

    我发现了我的错误并纠正了它。首先,控制根本不会尝试。所以修复了这个问题,现在只要 try 块失败并相应地捕获屏幕截图,就会执行 catch 块。谢谢你们的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多