簡體   English   中英

Selenium 可以在 JUnit 測試失敗時截取屏幕截圖嗎?

[英]Can Selenium take a screenshot on test failure with JUnit?

當我的測試用例失敗時,尤其是在我們的構建服務器上,我想拍攝屏幕的圖片/屏幕截圖以幫助我調試稍后發生的事情。 我知道如何截取屏幕截圖,但我希望在 JUnit 中有一種方法可以在瀏覽器關閉之前在測試失敗時調用我的takeScreenshot()方法。

不,我不想編輯我們無數的測試來添加 try/catch。 我想,我可能,只是可能被談論成一個注釋。 我所有的測試都有一個共同的父類,但我想不出我能做些什么來解決這個問題。

想法?

一些快速搜索使我找到了這個:

http://blogs.steeplesoft.com/posts/2012/grabbing-screenshots-of-failed-selenium-tests.html

基本上,他建議創建一個 JUnit4 Rule ,將測試Statement包裝在他調用的 try/catch 塊中:

imageFileOutputStream.write(
    ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));

這對你的問題有用嗎?

如果您想快速將此行為添加到運行中的所有測試中,您可以使用RunListener接口來偵聽測試失敗。

public class ScreenshotListener extends RunListener {

    private TakesScreenshot screenshotTaker;

    @Override
    public void testFailure(Failure failure) throws Exception {
        File file = screenshotTaker.getScreenshotAs(OutputType.File);
        // do something with your file
    }

}

像這樣將偵聽器添加到您的測試運行器中...

JUnitCore junit = new JUnitCore();
junit.addListener(new ScreenshotListener((TakesScreenShots) webDriver));

// then run your test...

Result result = junit.run(Request.classes(FullTestSuite.class));

如果你想在測試失敗時截圖,添加這個類

import java.io.File;

import java.io.IOException;

import java.util.UUID;

import org.apache.commons.io.FileUtils;

import org.junit.rules.MethodRule;

import org.junit.runners.model.FrameworkMethod;

import org.junit.runners.model.Statement;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

public class ScreenShotOnFailure implements MethodRule {

    private WebDriver driver;

    public ScreenShotOnFailure(WebDriver driver){
        this.driver = driver;
    }

    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    statement.evaluate();
                } catch (Throwable t) {
                    captureScreenShot(frameworkMethod.getName());
                    throw t;
                }
            }

            public void captureScreenShot(String fileName) throws IOException {
                File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                fileName += UUID.randomUUID().toString();
                File targetFile = new File("./Screenshots/" + fileName + ".png");
                FileUtils.copyFile(scrFile, targetFile);
            }
        };
    }
}

在所有測試之前,您應該使用此規則:

@Rule
public ScreenShotOnFailure failure = new ScreenShotOnFailure(driver));

@Before
public void before() {
   ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM