Скриншоты Allure report не делаются, если тест не пройден - PullRequest
0 голосов
/ 26 января 2020

Я создал TestListener и внедрил метод, который должен делать снимок экрана при неудачном завершении теста. Но если тест не пройден, скриншот не берется, но я не знаю почему. Если вызывается метод takeScreenshot (), снимок экрана не сохраняется в привлекательных результатах. Ниже я публикую код TestListener и TestBase:

public class TestListener extends TestBase implements ITestListener {


@Override
public void onTestFailure(ITestResult result) {
    Object testClass = result.getInstance();
    driver = ((TestBase) testClass).getTestDriver();
    if(driver != null) {
        takeScreenshot();
    }
}

@Override
public void onTestSkipped(ITestResult result) {

}

@Attachment(value = "Page screenshot", type = "image/png")
public byte[] takeScreenshot() {
    setThisDriver(driver);
    return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
}




public class TestBase {

public WebDriver driver;

public static Properties prop;

public static String env;

public static String url;

public TestBase() {
    try {
        this.prop = new Properties();
        FileInputStream ip = new FileInputStream(
                "src/main/java/config/env.properties");
        this.prop.load(ip);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void initialization() {
    System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver");
    System.setProperty("http.agent", "Mozilla/5.0");
    FirefoxBinary firefoxBinary = new FirefoxBinary();
    File downloadsDir = new File("src/main/documents/");
    //firefoxBinary.addCommandLineOptions("--headless");
    FirefoxOptions options = new FirefoxOptions();
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
            "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("browser.download.manager.focusWhenStarting", false);
    profile.setPreference("browser.download.useDownloadDir", true);
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
    profile.setPreference("browser.download.manager.closeWhenDone", true);
    profile.setPreference("browser.download.manager.showAlertOnComplete", false);
    profile.setPreference("browser.download.manager.useWindow", false);
    profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
    profile.setPreference("pdfjs.disabled", true);
    //options.setHeadless(true);
    options.setBinary(firefoxBinary);
    //options.setProfile(profile);
    this.driver = new FirefoxDriver(options);
    try {
        this.driver.manage().window().maximize();
        this.driver.manage().deleteAllCookies();
    }
    catch (WebDriverException e) {
        System.out.println(e.toString());
        this.driver.quit();
    }

}

public WebDriver getTestDriver() {
    return this.driver;
}

public void setThisDriver(WebDriver webDriver) {
    this.driver = webDriver;
}


public String getCurrentDate() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
            Calendar.getInstance().getTime());
    return timeStamp;
}

public void captureScreenshots(String result) {
    try {
        TakesScreenshot ts = (TakesScreenshot) driver;
        File source = ts.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(source, new File("src/screenshots/" + getCurrentDate() + ".png"));
        System.out.println("Takes screenshot");

    } catch (Exception e) {
        System.out.println("Exception" + e.getMessage());
    }
}

1 Ответ

0 голосов
/ 30 января 2020

Хорошо, если у кого-то есть такая же проблема, вот ответ. Конфигурация была в порядке, но если мы хотим создать отчет со скриншотами, мы должны запустить тесты из командной строки, используя: ./gradlew clean test и ./gradlew allureReport для генерации отчета.

...