WebDriver应用实例(java)——精确比较网页截图图片

        在测试过程中,常常需要对核心页面进行截屏,并且使用测试过程中的截图和以前测试过程中的截图进行比对。如果能精确匹配,则认为对比成功;如果页面发生任何细微的变化,都会认为不匹配。

        具体实例如下:

package cn.om.webdriverapi;

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 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.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestCompareScreenShot {
	WebDriver driver;
	String url;

	@Test
	public void testImageComparison() throws InterruptedException, IOException  {
		driver.get(url);
		//对baidu首页进行截屏,保存为baiduHomePage_actual.jpg
		File screenshot=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		Thread.sleep(3000);
		FileUtils.copyFile(screenshot, new File("F:\\workspace\\WebDriver API\\baiduHomePage_actual.jpg"));
		
		//打开截图图片和预期图片
		File fileInput=new File("F:\\workspace\\WebDriver API\\baiduHomePage_actual.jpg");
		File fileOutput=new File("F:\\workspace\\WebDriver API\\baiduHomePage_expected.jpg");
		
		
		/*对两个文件进行像素比对的算法实现。
		 * 获取文件的像素大小,然后使用循环的方式将两张图的所有项目进行一一比对,如有任何一个像素不相同,则退出循环
		 * 将matchFlag变量的值设定为fale
		 * 最后通过断言判断matchflag是否为true,如果为true,则表示两张相同。如果是flase表示两张图片并不是完全匹配。
		 */
		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.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		url="http://www.baidu.com";
	}

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

}

猜你喜欢

转载自blog.csdn.net/vikeyyyy/article/details/80192765
今日推荐