Selenium網頁自動化程式如何計算網頁載入時間?

Selenium網頁自動化程式如何計算網頁載入時間?

這篇文章主要說明,當自動化測試程式啟動瀏覽器執行的時候,如何在執行的過程中,

將網頁所載入的時間記錄下來做為事後效能分析參考的依據。最後,舉一個完整的程式範例說明。

 

 

測試情境

我們將啟動 fireFox瀏覽至 http://news.yahoo.com/

執行過程中記錄網頁啟動的時間與結束的時間。之後將這兩個時間相減,就會得到網頁載入的時間。

程式說明

這裡主要用到一個小技巧, System.currentTimeMillis(),透過這個API就可以讀取目前系統時間。

最後相減就會得到整體執行時間 totalTime = endTime – startTime;

startTime = System.currentTimeMillis();

endTime = System.currentTimeMillis();

long totalTime = endTime – startTime;

完整程式範例

[pastacode lang=”java” message=”Selenium TotalTime” highlight=”” provider=”manual”]

package mySelenium;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class PageLoadingTime {
	
	WebDriver driver;
	long startTime, endTime;
	
	@Before
	public void setUp()
	{
		driver = new FirefoxDriver();
		
		// Get the Start Time
		startTime = System.currentTimeMillis();
		
		driver.get("http://news.yahoo.com/");
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
		// Get the end time
		endTime = System.currentTimeMillis();

		
	}
	
		
  
	@Test
	public void testPrintTotalTime(){
		
		// Get the period of time and print it
		long totalTime = endTime - startTime;
	    System.out.println("Total Page Load Time: " + totalTime + " milliseconds");
		
	  }
	
	@After
	public void teadDown()
	{
		//	Close the current window, quitting the browser
		driver.close();
		//Quits this driver, closing every associated window that was open.
		driver.quit();
	}
  
}

[/pastacode]

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *