您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
Selenium自動化之截圖保存現(xiàn)場
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2016/4/14 16:31:34 ] 推薦標簽:軟件測試技術(shù) 功能測試

  前提:
  自動化中截圖功能是直接呈現(xiàn)問題,幫助定位的一種很好的手段。
  下面總結(jié)一下,我用Selenium做自動化是如何保留截圖的。
  環(huán)境和工具:
  eclipse、Selenium、Testng、Reporter
  場景:
  使用Selenium提供的方法來截取屏幕,使用Reporter監(jiān)聽器,當(dāng)用例執(zhí)行失敗時截圖,截圖以出錯時系統(tǒng)時間和出錯方法的拼接命名,截圖保存到項目目錄下snapshot
  1、編寫獲取屏幕截圖類
ScreenShot.java
package Tool;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.Reporter;
public class ScreenShot {
public static void takeScreenshot(String screenPath, WebDriver driver) {
try {
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(screenPath));
} catch (IOException e) {
System.out.println("Screen shot error: " + screenPath);
Reporter.log("該錯誤可以查看截圖:"+screenPath);
}
}
public static void takeScreenshot(WebDriver driver) {
String screenName=CommonFunction.getFormatDate()+".jpg";
File dir = new File("snapshot");
if (!dir.exists())
dir.mkdirs();
String screenPath = dir.getAbsolutePath() + "/" + screenName;
takeScreenshot(screenPath, driver);
}
}
  2、修改監(jiān)聽器,當(dāng)用例執(zhí)行失敗時,添加代碼調(diào)用上面方法保留截圖。
  我是自定義了一個監(jiān)聽器,繼承了TestListenerAdapter ,然后重寫了onTestFailure
ScrennFailtureListener.java
package Tool;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import TestCase.FirefoxInitPre;
public class ScrennFailtureListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult tr) {
System.out.println("執(zhí)行onTestFailure");
ScreenShot.takeScreenshot(FirefoxInitPre.driver);
super.onTestFailure(tr);
}
}

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