首页 > Web开发 > 详细

WebDriver高级应用实例(4)

时间:2019-03-14 15:52:20      阅读:177      评论:0      收藏:0      [点我收藏+]

  6.1精确比较网页截图图片

  目的:对于核心界面进行截屏,并且使用测试过程中的截图和以前测试过程中的截图进行比较。确认页面是否发生了改变

  被测网页的网址:

  http://www.baidu.com

  Java语言版本的API实例代码  

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;

import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestCompareImages {
  WebDriver driver;
  String url = "http://www.baidu.com";
@Test
public void testImageComparison() throws InterruptedException, IOException {
  File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  Thread.sleep(3000);
  //对百度首页进行截屏
  FileUtils.copyFile(screenshot, new File("e:\\baiduHomePage_actual.jpg"));
  //生成两个文件对象,一个是期望图片(期望图片需自己先准备),一个是测试过程中产生的图片
  File fileInput = new File("e:\\baiduHomePage_expected.jpg");
  File fileOutPut = new File("e:\\baiduHomePage_actual.jpg");
  /*
  * 以下部分分为两个文件进行像素比对的算法实现,获取文件的像素个数大小,然后使用循环对两张图片进行比对如果有任何一个像素不相同则退出循环
  * */
  BufferedImage bufileInput = ImageIO.read(fileInput);
  DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
  int sizefileInput = dafileInput.getSize();
  BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
  DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
  int sizefileOutPut = dafileOutPut.getSize();
  Boolean matchFlag = true;
  if(sizefileInput == sizefileOutPut){
  for(int j = 0; j<sizefileInput;j++){
    if(dafileInput.getElem(j)!= dafileOutPut.getElem(j)){
      matchFlag = false;
      break;
      }
    }
  }
  else
  matchFlag = false;
  Assert.assertTrue(matchFlag,"测试过程中的截图和期望的截图并不一致");
}
@BeforeMethod
public void beforeMethod() {
  System.setProperty("webdriver.chrome.driver", "D:\\WebDriver\\chromedriver_win32\\chromedriver.exe");
  driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get(url);
}

@AfterMethod
public void afterMethod() {
  driver.quit();
}

}

WebDriver高级应用实例(4)

原文:https://www.cnblogs.com/z-zzz/p/10530439.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!