截图是做测试的基本技能,在有BUG的地方,截个图,保留失败的证据,也方便去重现BUG。所以,在自动化的过程中,也要能截图,也要能在我们想要截取的地方去截图,且能在错误产生时,自动的截图。
示例:
脚本中的调用:
错误时截图:
提示:结合testng的监听器,来实现错误时截图,在之后的博客中会做介绍。
具体代码如下:
ScreenShot.java文件:
package com.selenium.utils; 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; public class ScreenShot { public WebDriver driver; public ScreenShot(WebDriver driver) { this.driver = driver; } public void takeScreenShot(String screenPath) { try { File srcFile = ((TakesScreenshot) driver) .getScreenshotAs(OutputType.FILE); FileUtils.copyFile(srcFile, new File(screenPath)); } catch (IOException e) { System.out.println("Screen shot error: " + screenPath); } } public void takeScreenShot() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String screenName = String.valueOf(sdf.format(new Date().getTime()) + ".jpg"); File dir = new File("test-output/snapshot"); if (!dir.exists()) { dir.mkdir(); } String screenPath = dir.getAbsolutePath() + File.separator + screenName; this.takeScreenShot(screenPath); } }
代码中的使用方式:
package com.selenium.test; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.selenium.utils.Assertion; import com.selenium.utils.Log; import com.selenium.utils.ScreenShot; public class testAssertion { public static WebDriver Driver; @Test(dataProvider = "name") public void testBaidu(String text) { startFireFox("http://baidu.com"); System.out.println(text); Driver.findElement(By.id("kw")).sendKeys(text); ScreenShot image = new ScreenShot(Driver); image.takeScreenShot(); closeFireFox(); } @DataProvider public Object[][] name() { return new Object[][] { { "zhangSan" }, { "liSi" } }; } public static void startFireFox(String url) { Driver = new FirefoxDriver(); Driver.manage().window().maximize(); Driver.navigate().to(url); } public static void closeFireFox() { Driver.close(); } }
最后打个广告,不要介意哦~
最近我在Dataguru学了《软件自动化测试Selenium2》网络课程,挺不错的,你可以来看看!要是想报名,可以用我的优惠码 G863,立减你50%的固定学费!
链接:http://www.dataguru.cn/invite.php?invitecode=G863