java - 使用Java将methodName添加到selenium失败的屏幕截图名称

标签 java selenium

我试图将失败的 methodName 添加到使用 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);
    }
}

最佳答案

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

关于java - 使用Java将methodName添加到selenium失败的屏幕截图名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18841145/

相关文章:

java - RMI激活奇怪的问题

javascript - Python:Selenium 模拟 onclick

Java - 创建动态变量表,我可以轻松回调变量

java - Selenium - 如何在高频刷新网页上正确获取元素

java - 如何从 JAX-WS 中的 Spring 方面访问 SOAPMessage?

c# - 处理视频文件每个像素的单个颜色信息

java - 单例模式执行排序问题

selenium - 屏幕分辨率会破坏 Selenium 测试吗?

python - 如何在 Python Selenium 中获取 WebElement 的类名?

java - 枚举作为一个类(class)?