然后,我們?cè)诩右粋(gè)封裝類, 將截圖方法放進(jìn)去。
WebDriverWrapper.screenShot :
/**
* Function to take the screen shot and save it to the classpath dir.
* Usually, you will find the png file under the project root.
*
* @param driver
* Webdriver instance
* @param desc
* The description of the png
*/
public static void screenShot(WebDriver driver, String desc) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String dateString = formatter.format(currentTime);
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
desc = desc.trim().equals("") ? "" : "-" + desc.trim();
File screenshot = new File("screenshot" + File.separator
+ dateString + desc + ".png");
FileUtils.copyFile(scrFile, screenshot);
} catch (IOException e) {
e.printStackTrace();
}
}
下面,是添加 Junit 的 TestRule:
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.openqa.selenium.WebDriver;
public class TakeScreenshotOnFailureRule implements TestRule {
private final WebDriver driver;
public TakeScreenshotOnFailureRule(WebDriver driver) {
this.driver = driver;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
}
catch (Throwable throwable) {
WebDriverWrapper.screenShot(driver, "assert-fail");
throw throwable;
}
}
};
}
}
代碼很簡(jiǎn)單,在拋出 evalate 方法的錯(cuò)誤之前,截圖。
然后是使用這個(gè) TestRule, 很簡(jiǎn)單,只要在你的 測(cè)試用例里面加入:
public class MyTest {
...
@Rule
public TestRule myScreenshot = new TakeScreenshotOnFailureRule(driver);
...
@Test
public void test1() {}
@Test
public void test2() {}
...
}
即可。關(guān)于 Junit 的 Rule 請(qǐng)自行 google!
兩則的比較
總得來(lái)說(shuō),兩種方法都很方便, 也很有效果, 基本都能截圖成功。
不同之處在于,
RemoteWebDriver 監(jiān)聽(tīng)器是在 RemoteWebDriver 拋出異常的時(shí)候截圖。
TestRule 是在 assert 失敗的時(shí)候截圖。
我在項(xiàng)目中早是用第一種方法,后來(lái)改用第二種,主要是因?yàn),在自定義的監(jiān)聽(tīng)器里, 它遇到所有的異常都會(huì)截圖,這個(gè)時(shí)候,如果你用了 condition wait 一個(gè) Ajax 的元素, 那會(huì)很悲劇,你會(huì)發(fā)現(xiàn)在你的目錄下面有無(wú)數(shù)的截圖。當(dāng)初我沒(méi)有找到解決方法,期待有人提出。