2016-12-08 30 views
0

當我收到異常時,測試運行立即結束,並且任何以下測試驗證都會被跳過。我想捕捉異常,處理它,然後繼續工作流程。如何讓TestNG繼續對異常執行測試?

在下例中,如果objPage.Method1();引發異常,則整個@Test立即結束。我想catch執行,然後移動到objPage.Method2()

@Test (enabled=true) 
public void MyClientsFunctions() throws Exception { 
    ExtentTest t = ReportFactory.getTest(); 
    try { 

     Login objPage = new PageObject(driver); 

     //this method throws exception 
     objPage.Method1(); 
      if (x=y) 
      t.log(LogStatus.PASS, "Pass message"); 
      else 
      t.log(LogStatus.FAIL,"Fail message"+ screenshotMethod()); 

     objPage.Method2(); 
      if (a=b) 
      t.log(LogStatus.PASS, "Pass message"); 
      else 
      t.log(LogStatus.FAIL,"Fail message"+ screenshotMethod()); 

    } catch (Exception e) { 
     t.log(LogStatus.ERROR, "Exception found: " + e.getMessage() + screenshotMethod()); 
    } 
} 

我正在使用PageFactory和ExtentReports。我使用if語句來報告失敗。沒有斷言。我相信,如果斷言失敗,結果是一樣的,測試結束。

+0

方法1,2和3應該都是他們自己的單元測試,而不是集中到單個測試中。另外,爲什麼不使用Assert,然後在catch中記錄錯誤(Throwable t)...這樣,當在method1上測試失敗時,方法2和3將繼續執行...並且您的報告將顯示1失敗,跳過0跑3等 – labheshr

+0

更高的ups希望沒有斷言,更多的可定製報告(我也不喜歡它)。我使用的是PageFactory,因此方法1,2,3是輸入電子郵件和密碼等整個工作流程的簡單部分。所以他們沒有得到他們自己的@Tests。就像不是每個Assert都需要它自己的測試一樣。 – dsidler

+1

然後在'Method1()'附近做一個'try catch' ...有什麼問題? – JeffC

回答

0

將objPage.Method2()寫入最終塊,然後執行。

+0

我認爲這是一個很好的答案給出的例子。但在我的情況下,我有很多有兩種以上的方法,參見上文。 – dsidler

0

感謝@JeffC指引我朝着正確的方向前進。

對我而言,我從頁面對象類中調用至少有十幾個動作方法。我不能把他們全部放在自己的最後一塊。

我所做的是將每個工作流程(一個或多個方法,然後驗證)放在它自己的try/catch中。 catch包含日誌/截圖,然後重定向到下一個工作流需要執行的頁面。所以,我們嘗試/ catch(登錄),try/catch(enterHoursWorked)等等......正如其他人所說,這很醜陋,但在我的情況下,它的工作原理。現在將例外添加到日誌中,並且執行下一個工作流程

public void MyClientsFunctions() throws Exception { 
    ExtentTest t = ReportFactory.getTest(); 
    try { 

     Login objPage = new PageObject(driver); 

     // this method throws exception 
     try { 
      objPage.Login(); 
      if (x = y) 
       t.log(LogStatus.PASS, "Pass message"); 
      else 
       t.log(LogStatus.FAIL, "Fail message" + screenshotMethod()); 
     } catch (Exception e) { 
      t.log(LogStatus.ERROR, "Exception found: " + e.getMessage() + screenshotMethod()); 
      objPage.BackToHomePage(); 
     } 
     try { 
      objPage.EnterHoursWorked(); 
      if (a = b) 
       t.log(LogStatus.PASS, "Pass message"); 
      else 
       t.log(LogStatus.FAIL, "Fail message" + screenshotMethod()); 
     } catch (Exception e) { 
      t.log(LogStatus.ERROR, "Exception found: " + e.getMessage() + screenshotMethod()); 
      objPage.BackToHomePage(); 
     } 

    } catch (Exception e) { 
     t.log(LogStatus.ERROR, "Exception found: " + e.getMessage() + screenshotMethod()); 
    } 
}