2 回答

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>

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中的逻辑不应该被意外问题打断。
添加回答
举报