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

I need to always logout of my application when my test fails or an exception occurs. How should i do it?

我有一个测试用例如下:

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

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

我尝试将注销逻辑放在@AfterMethod 中。它工作正常,但这是在 @AfterMethod 这样的配置方法中编写测试代码的最佳实践吗?

我在 C# 工作,但这个概念很可能在所有语言中都是相同的。就我而言,我在我的基础 class 中使用所谓的 "TearDown" 标记来标记一种方法,该方法在测试后应始终 运行 。所有测试都从基础 class 继承此方法并进行相应处理。在过去的几年里,这很有效,据我所知,任何类似的概念都被认为是最佳实践。

在伪代码中:

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

将注销放在 @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。在 class 中实现 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>