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

  然后,我們?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)聽器是在 RemoteWebDriver 拋出異常的時(shí)候截圖。

  TestRule 是在 assert 失敗的時(shí)候截圖。

  我在項(xiàng)目中早是用第一種方法,后來(lái)改用第二種,主要是因?yàn),在自定義的監(jiān)聽器里, 它遇到所有的異常都會(huì)截圖,這個(gè)時(shí)候,如果你用了 condition wait 一個(gè) Ajax 的元素, 那會(huì)很悲劇,你會(huì)發(fā)現(xiàn)在你的目錄下面有無(wú)數(shù)的截圖。當(dāng)初我沒有找到解決方法,期待有人提出。

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