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

  try {

  out = new FileOutputStream(of);

  out.write(new Base64Encoder()

  .decode(((ScreenshotException) cause)

  .getBase64EncodedScreenshot()));

  }

  catch (Exception e) {

  e.printStackTrace();

  }

  finally {

  try {

  out.close();

  }

  catch (IOException e) {

  e.printStackTrace();

  }

  }

  }

  }

  }

  主要看 onException 這個(gè)方法的實(shí)現(xiàn),很明顯, 我們捕獲了這個(gè)異常, 然后通過(guò)強(qiáng)制轉(zhuǎn)換將圖片提取出來(lái),寫(xiě)入硬盤(pán)。

  然后是使用這個(gè)監(jiān)聽(tīng)器, 通常會(huì)在 setup 方法里面將這個(gè)監(jiān)聽(tīng)器注冊(cè)到 WebDriver 中去, 看代碼:

  @Test

  public void setup(){

  String remote_driver_url = "http://localhost:4444/wd/hub";

  DesiredCapabilities capability = null;

  capability = DesiredCapabilities.firefox();

  WebDriverEventListener eventListener = new CustomWebDriverEventListener ();

  WebDriver driver = new EventFiringWebDriver(new RemoteWebDriver(new URL(

  remote_driver_url), capability)).register(eventListener);

  }

  在這之后,如果運(yùn)行出錯(cuò), WebDriver 拋出異常會(huì)在相應(yīng)的 classpath 下面生成 png 的截圖。

  自定義 TestRule

  和自定義 WebDriver 監(jiān)聽(tīng)器不同, 自定義 TestRule 只有在這個(gè) Rule 被執(zhí)行的時(shí)候, 才去做一些我們預(yù)設(shè)的 CallBack。 所以這個(gè)截圖動(dòng)作,對(duì)于 WebDriver 而言, 是主動(dòng)的。 那么,我們需要自定義一個(gè) RemoteWebDriver 來(lái)實(shí)現(xiàn)截圖功能。 WebDriver 自身提供了 TakesScreenshot 這個(gè)接口, 我們只要實(shí)現(xiàn)它可以了, 看代碼:

  import java.net.URL;

  import org.openqa.selenium.OutputType;

  import org.openqa.selenium.TakesScreenshot;

  import org.openqa.selenium.WebDriverException;

  import org.openqa.selenium.remote.CapabilityType;

  import org.openqa.selenium.remote.DesiredCapabilities;

  import org.openqa.selenium.remote.DriverCommand;

  import org.openqa.selenium.remote.RemoteWebDriver;

  public class CustomRemoteWebDriver extends RemoteWebDriver implements

  TakesScreenshot {

  public CustomRemoteWebDriver(URL url, DesiredCapabilities dc) {

  super(url, dc);

  }

  @Override

  public X getScreenshotAs(OutputType target)

  throws WebDriverException {

  if ((Boolean) getCapabilities().getCapability(

  CapabilityType.TAKES_SCREENSHOT)) {

  return target

  .convertFromBase64Png(execute(DriverCommand.SCREENSHOT)

  .getValue().toString());

  }

  return null;

  }

  }

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