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

时间:2013-09-17 04:07:00

标签: java selenium

我正在尝试将失败的methodName添加到使用java运行selenium时发生故障时所采用的屏幕截图。我已经尝试了网络上的多个解决方案,但他们最终都返回了规则类或methodName的methodName。我不知道怎么做,所以截图文件名返回'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);
    }
}

1 个答案:

答案 0 :(得分:0)

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