亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當我的測試失敗或發生異常時,我需要始終注銷我的應用程序。我該怎么做?

當我的測試失敗或發生異常時,我需要始終注銷我的應用程序。我該怎么做?

躍然一笑 2022-09-28 15:51:55
我有一個測試用例如下:@Testpublic void checkSomething(){//line1//line2//line3//line4[Exception occurs here]//line5//line6//line7 homepage.Logout();}現在,例如,如果第 4 行中發生異常,則我的應用程序將永遠不會注銷 [line7]。這將導致我的進一步測試用例失敗,因為它們將無法登錄,因為用戶會話將處于活動狀態。我如何使注銷始終在測試過早失敗時發生?我嘗試將注銷邏輯放在@AfterMethod中。它工作正常,但這是在配置方法(如@AfterMethod)中編寫測試代碼的最佳實踐嗎?
查看完整描述

2 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

將注銷放入會很好,但請確保您以有效的方式執行此操作。@AfterMethod

  • 如果僅測試失敗,則檢查注銷

  • 避免使用嘗試捕獲,因為它等待給定的時間(隱式等待)來檢查存在的元素,然后進入捕獲塊而不是使用列表

引用以下代碼使用@AfterMethod

 @AfterMethod 

 public void screenShot(ITestResult result){

       if(ITestResult.FAILURE==result.getStatus()){

            List<WebElement> username = driver.findElement(By.locator); // element which displays if user is logged in

            if(!username.isEmpty())

                // steps to logout will go here

            }

       }

  }

另一種選擇是您可以使用TestNG監聽器。在類中實現并重寫方法,如下所示ITestListeneronTestFailure


@Override

public void onTestFailure(ITestResult result) {

      if(ITestResult.FAILURE==result.getStatus()){

            List<WebElement> username = driver.findElement(By.locator); // element which displays if user is logged in

            if(!username.isEmpty())

                // steps to logout will go here

            }

       }

}

在測試中添加下面的標簽.xml


<listeners>

   <listener class-name="com.pack.listeners.TestListener"/> // your created class name with package which implemented ITestListener

</listeners>


查看完整回答
反對 回復 2022-09-28
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

我使用 C# 工作,但概念在所有語言中很可能是相同的。在我的例子中,我在我的基類中使用所謂的“TearDown”標簽來標記一個應該在測試后始終運行的方法。所有測試都從基類繼承此方法,并進行相應的處理。在過去的幾年里,這已經很好了,據我所知,任何類似的概念都被認為是最佳實踐。


在偽代碼中:


    [TearDown]

    public void Cleanup()

    {

        try

        {

            Logout();

            OtherStuffLikeClosingDriver();

        }

        catch (Exception ex)

        {

            Log(ex);                            // Obviously, this logging function needs to generate logs that are easily readable, based on the given exception.

            FinishTest(testInstance, testName); // Handles critical flows that should always be finished (and "should" not be able to error out)

            throw ex;                           // In my case, throwing the exception again makes sure that the exception is shown in the test output directly. This often speeds up the first diagnose of a failed test run.

        }

    }

只要確保處理異常等:@AfterMethod中的邏輯不應該被意外問題打斷。


查看完整回答
反對 回復 2022-09-28
  • 2 回答
  • 0 關注
  • 97 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號