1. 程式人生 > >WebDriver應用例項(java)——精確比較網頁截圖圖片

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();
	}

}