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

  然后,我們在加一個封裝類, 將截圖方法放進去。

  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;

  }

  }

  };

  }

  }

  代碼很簡單,在拋出 evalate 方法的錯誤之前,截圖。

  然后是使用這個 TestRule, 很簡單,只要在你的 測試用例里面加入:

  public class MyTest {

  ...

  @Rule

  public TestRule myScreenshot = new TakeScreenshotOnFailureRule(driver);

  ...

  @Test

  public void test1() {}

  @Test

  public void test2() {}

  ...

  }

  即可。關(guān)于 Junit 的 Rule 請自行 google!

  兩則的比較

  總得來說,兩種方法都很方便, 也很有效果, 基本都能截圖成功。

  不同之處在于,

  RemoteWebDriver 監(jiān)聽器是在 RemoteWebDriver 拋出異常的時候截圖。

  TestRule 是在 assert 失敗的時候截圖。

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

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