为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 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 关注
  • 116 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号