当测试失败或发生异常时,我需要始终注销我的应用程序。我该怎么办?

问题描述 投票:0回答:2

我有一个测试用例如下:

@Test
public void checkSomething()
{
//line1
//line2
//line3
//line4[Exception occurs here]
//line5
//line6
//line7 homepage.Logout();
}

现在,如果例如在line4中发生异常,那么我的应用程序将永远不会注销[line7]。这将导致我的进一步测试用例失败,因为他们将无法登录,因为用户会话将处于活动状态。如何在测试过早失败时始终发生注销?

我尝试将注销逻辑放在@AfterMethod中。它工作正常,但是在@AfterMethod等配置方法中编写测试代码的最佳做法是什么?

java selenium testing testng
2个回答
1
投票

@AfterMethod注销会很好,但要确保你以有效的方式这样做。

  • 如果仅测试失败,请检查注销
  • 避免使用try catch因为它等待给定时间(ImplicitWait)来检查元素存在然后进入catch块而不是使用List

使用@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 Listener。在类中实现ITestListener并覆盖onTestFailure方法,如下所示

@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
            }
       }
}

在testng.xml中添加以下标记

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

0
投票

我在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中的逻辑不应被意外问题打断。

© www.soinside.com 2019 - 2024. All rights reserved.