首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Java将methodName添加到selenium失败的截图名称中

使用Java将methodName添加到selenium失败的截图名称中
EN

Stack Overflow用户
提问于 2013-09-17 12:07:00
回答 1查看 865关注 0票数 1

我正在尝试将失败的methodName添加到使用java运行selenium时发生故障时拍摄的屏幕截图中。我在网上尝试了多种解决方案,但它们最终都返回了规则类的methodName或methodName。我不知道怎么做,所以截图文件名返回'shouldFail_date.png‘。

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2013-09-19 02:59:42

您可以使用一种高效的selenium testing-frameworks - ISFW,它基于testng并根据您的需要提供描述性报告。以下是Overview Detail Report的一些快照

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18841145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档