在任何网页测试人员中,执行效果最好的操作之一就是对网页进行截图。 每当测试人员发现并报告错误时,如果不支持该问题的屏幕截图甚至视频,就不会认真对待该错误。 不论您进行的测试类型是什么,包括硒自动化测试,都是如此。
在自动化测试中,特别是在典型的测试运行可能涉及数百个命令和测试用例的情况下,关键断言处的自动屏幕截图对于确保开发人员和测试人员确保按需执行每个测试用例都非常重要。 这些证明又被用于调试,以找出出了什么问题以及失败的原因。 对于使用selenium进行的自动化测试 ,这些屏幕截图有助于区分故障是由于应用程序故障还是脚本故障。
现在说了这一点,当我们说截图时,我们可能意味着捕获屏幕任何部分的图像,包括所讨论元素的图像,甚至是整个页面的屏幕截图。 因此,在本文中,我们将研究如何使用Selenium WebDriver自动化脚本为不同目的拍摄网页的自动屏幕截图。 首先,有四种使用Selenium Webdriver捕获屏幕快照图像的主要方法。 如 :
- 可视区域的屏幕截图
- 全屏截图,即捕获整个网页的截图
- 所需的webElement的屏幕截图
- 支持AUT屏幕截图的基于云的平台
自动硒测试脚本,用于拍摄可见区域的屏幕截图
这是在自动化下获取应用程序屏幕快照的最常用方法,也是最简单的一种方法。 Selenium提供了一种现成的功能,称为TakeScreenShot界面,可用于拍摄可视区域的屏幕截图。
您可以在此处检查界面的详细信息。
该接口提供了一种称为getScreenshotAs的方法,该方法有助于捕获屏幕截图并将其存储在所需的位置。
这是捕获屏幕截图的语法:
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
为了将拍摄的屏幕快照存储到文件中,使用以下语句:
FileUtils.copyFile(screenshotFile, new File("path of the file you want to save the screenshot to"));
就是这个! 仅需两个语句,您就可以截取屏幕截图。 让我们将此步骤合并到代码段中。 下面的示例展示了Airbnb的住宿详情页面示例,在该示例中,我们对可见屏幕进行了截图:
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class ViewableScreenshotExample {
WebDriver driver;
@BeforeTest
public void setupUrl()
{
System.setProperty( "webdriver.chrome.driver" , ".\\Driver\\chromedriver.exe" );
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait( 10 , TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get( " https://www.airbnb.co.in/s/India/ " );
}
@Test
public void performAction() throws InterruptedException
{
//Scroll down the page
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript( "window.scrollBy(0,250)" , "" );
//open the stay details page
driver.findElement(By.xpath( "//div[contains(text(), 'Sea Hut Homestay with Aircon')]" )).click();
Thread.sleep( 1500 );
//Switch to the required tab
ArrayList<String> ta = new ArrayList<String> (driver.getWindowHandles());
int i=ta.size();