您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 >
WebDriver之測試失敗自動截圖
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2013/4/9 17:09:56 ] 推薦標(biāo)簽:

  webDriver 測試的時候頭疼的是調(diào)試。但也遠不及運行的時候出錯,再回頭調(diào)試來的痛苦?偹苤, web 自動化的代碼都非常脆弱,一份代碼一會運行失敗,一會運行成功也是很正常的事情?偟膩碚f造成案例運行失敗的原因大抵有兩點:

  環(huán)境問題: 比如網(wǎng)絡(luò)不穩(wěn)定啊

  代碼變動: 比如某個元素不在

  遇到 bug :這是真的發(fā)現(xiàn) bug 了

  無論哪一種,遇到了都需要花一番時間去 debug。那如果這個時候有一張運行時候出錯的截圖,那一目了然了。(即便不一目了然,也有很多幫助)

  在運行出錯的時候,捕獲錯誤并截圖有兩種思路:

  自定義一個 WeDdriver 的監(jiān)聽器,在出異常的時候截圖。

  利用 Juint 的 TestRule, 自定義一個 Rule 在運行失敗的時候截圖。

  自定義監(jiān)聽器

  截圖的原理

  截圖需要用到 RemoteWebDriver。在 Selenium 官方我們可以找到:

  One nice feature of the remote

  webdriver is that exceptions often

  have an attached screen shot, encoded

  as a Base64 PNG. In order to get this

  screenshot, you need to write code

  similar to:

  public String extractScreenShot(WebDriverException e) {

  Throwable cause = e.getCause();

  if (cause instanceof ScreenshotException) {

  return ((ScreenshotException) cause).getBase64EncodedScreenshot();

  }

  return null;

  }

  意思是說,每個異常都是 ScreenshotException 的對象,轉(zhuǎn)碼一下可以用了。這是截圖的本質(zhì)。

  import java.io.File;

  import java.io.FileOutputStream;

  import java.io.IOException;

  import java.text.SimpleDateFormat;

  import java.util.Date;

  import org.openqa.selenium.WebDriver;

  import org.openqa.selenium.internal.Base64Encoder;

  import org.openqa.selenium.remote.ScreenshotException;

  import org.openqa.selenium.support.events.AbstractWebDriverEventListener;

  /**

  * This is an customized webdriver event listener.

  * Now it implements onException method: webdriver will take a screenshot

  * when it meets an exception. It's good but not so usable. And when we use

  * WebDriverWait to wait for an element appearing, the webdriver will throw

  * exception always and the onException will be excuted again and again, which

  * generates a lot of screenshots.

  * Put here for study

  * Usage:

  * WebDriver driver = new FirefoxDriver();

  * WebDriverEventListener listener = new CustomWebDriverEventListener();

  * return new EventFiringWebDriver(driver).register(listener);

  *

  * @author qa

  *

  */

  public class CustomWebDriverEventListener extends

  AbstractWebDriverEventListener {

  @Override

  public void onException(Throwable throwable, WebDriver driver) {

  Throwable cause = throwable.getCause();

  if (cause instanceof ScreenshotException) {

  SimpleDateFormat formatter = new SimpleDateFormat(

  "yyyy-MM-dd-hh-mm-ss");

  String dateString = formatter.format(new Date());

  File of = new File(dateString + "-exception.png");

  FileOutputStream out = null;

上一頁123下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd