1

我正在尝试将失败的方法名称添加到使用 java 运行 selenium 时发生故障时拍摄的屏幕截图。我在网上尝试了多种解决方案,但最终都返回了规则类的方法名或方法名。我不确定如何制作,因此屏幕截图文件名返回“shouldFail_date.png”。

package test;

import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ScreenShotRule extends TestWatcher {
    private WebDriver browser;

    public ScreenShotRule(WebDriver browser) {
        this.browser =  browser;
    }

    @Override
    protected void failed(Throwable e, Description description) {
        TakesScreenshot takesScreenshot = (TakesScreenshot) browser;

        File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
        File destFile = getDestinationFile();
        try {
            FileUtils.copyFile(scrFile, destFile);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    @Override
    protected void finished(Description description) {
        browser.close();
    }

    private File getDestinationFile() {
        Throwable t = new Throwable();
        String callerMethodName = t.getStackTrace()[1].getMethodName();
        DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
        String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
        new File(userDirectory).mkdirs();
        String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";

        return new File(absoluteFileName);
    }
}

package test;

import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScreenShotTest {
    private WebDriver browser = new FirefoxDriver();

    @Rule
    public ScreenShotRule screenShootRule = new ScreenShotRule(browser);

    @Test
    public void shouldFail() {
        browser.get("http://www.google.com");
        By link = By.partialLinkText("I do not expect to find a link with this text");
        browser.findElement(link);
    }
}
4

1 回答 1

0

您可以使用一种高效的selenium 测试框架- ISFW,它基于 testng 并根据您的需要提供描述性报告。以下是一些快照 概览 详细报告

于 2013-09-18T18:59:42.090 回答