如何在“重试”之后为失败的测试拍摄屏幕截图

时间:2014-12-30 13:43:25

标签: selenium-webdriver testng

在我们目前的框架中,我们正在截取屏幕onTestFailure。现在我们已经实施了' IRetryAnalyzer'使用它重新运行失败的测试。

当测试第一次失败时,它会拍摄屏幕并将其保存在指示“测试失败”的文件夹中,这可能会在下一次尝试中通过。

当我们提交最终的自动化报告时,我们还需要提交截图。在Screenshots文件夹中,当前传递(重新运行后)测试图像也会附加。

我们是否可以仅在测试失败时拍摄屏幕截图即使在重新运行后也忽略了之前的测试失败。

如果有其他选择,请建议。

以下是重试

的代码
@Override
public boolean retry(ITestResult result) {

    boolean iFlag=false;
    String resultString = result.getThrowable().toString();

    //Checking for specific reason of failure
    if (resultString.contains("NoSuchElementException") || resultString.contains("TimeoutException") ) {

        if (retryCount < maxRetryCount) {
            System.out.println("Retrying " + result.getName()+ " test for the "+ (retryCount + 1) + " time(s).");
            retryCount++;
            iFlag=true;
        } 

    } else {
        //making retryCount and maxRetryCount equal
        retryCount=0;
        maxRetryCount=0;
        iFlag=false;
    }

    return iFlag;
}

以下是On Test failure的代码

private static int retryCount=0;
private static int maxRetryCount=1;


@Override
public void onTestFailure(ITestResult result) {
    System.out.println("***** Error "+result.getName()+" test has failed *****");
    String methodName=result.getName().toString().trim();
    //takeScreenShot(methodName);
    driver=TestBase.getDriver();
    if( driver != null && retryCount == maxRetryCount) {
    takeScreenShot(driver, methodName);
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将onTestFailure/AfterMethodretry方法放在同一个类中,例如Retry或任何合适的名称。在那里,您可以将方法定义为:

private static int retryCount = 0;
private static int maxRetryCount = 2;    
@AfterMethod
public void tearDown(ITestResult result) throws IOException {
String methodname = result.getName();
WebDriver augmentedDriver = new Augmenter().augment(driver);
try {
    if (driver != null
            && ((RemoteWebDriver) driver).getSessionId() != null
            && !result.isSuccess() && retryCount == maxRetryCount) {
            File scrFile = ((TakesScreenshot) augmentedDriver)
                .getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File(("./test-output/archive/"
                + "screenshots/" + methodname + "_" + System.currentTimeMillis() + ".png")));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
            driver.quit();
    }
}

@Override
public boolean retry(ITestResult result) {
boolean res = false;
try {
    if (result.getThrowable().toString()
        .contains("NoSuchElementException")) {
    if (retryCount < maxRetryCount) {
        retryCount++;
        res = true;
    } else if (retryCount == maxRetryCount) {
        retryCount = 0;
        res = false;
    }
    } else {
    retryCount = 0;
    }
    return res;
} catch (Exception e) {
    return false;
}
}
相关问题