selenium截圖對比校驗方法


/**
對比圖片進行校驗是否成功
**/
package com.allin.pc;


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.junit.Assert;
import org.openqa.selenium.By;
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.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCompareImages {
    public WebDriver driver;
    
    private String baseUrl;
    
    @BeforeClass
    public void setUp(){
        baseUrl = "http://sogou.com";
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get(baseUrl);
        driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("123");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);    
    }
    
    @AfterClass
    public void tearDown(){
        driver.close();
    }
    
    
    @Test
    public void testImageComparison() throws InterruptedException, IOException{
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        Thread.sleep(3000);
        //對sogo首頁進行截屏
        FileUtils.copyFile(screenshot, new File("d:\\sogouHomePage_actual.jpg"));
        //生成了兩個文件對象,一個是期望的圖片,一個是實際測試過程中產生的圖片
        File fileInput = new File("d:\\sogouHomePage_expected.jpg");
        File fileOutPut = new File("d:\\sogouHomePage_actual.jpg");
        /*
         以下部分為兩個文件進行像素比對的算法實現,獲取文件的像素個數大小,然后使用循環的方式將兩張圖片的
         所有項目進行一一對比,如有任何一個像素不相同,則退出循環,將matchFlag變量的值設定為false,
         最后使用斷言語句判斷matchFlag是否為true。如果為true表示兩張圖片完全一致,如果為false
         表示兩張圖片並不是完全匹配
         */
        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 );
        }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM