使用Eclipse+TestNG+Selenium做web自動化測試

環境

系統 : MAC
IDE:Eclipse + TestNG (要求JDK7以上)
瀏覽器: Chrome 83.0.4103.61版本
Selenium 3.141.59版本

安裝Eclipse

https://www.eclipse.org/downloads/ 官網下載安裝

安裝TestNG eclipse plug-in

菜單欄 Help -> Install New Software,
install new software
Work with: 輸入 https://dl.bintray.com/testng-team/testng-eclipse/ (翻牆) 回車,等待搜索結果出來,然後勾選 TestNG, 點擊Next進行安裝。

*不要輸入 http://beust.com/eclipse ,這已經失效了 *

如果上面搜索超時, 可以從 https://github.com/cbeust/testng-eclipse/ 手動下載配置eclipse插件。

如果你要安裝Intelli J或者NetBeans插件,參照TestNG官網https://testng.org/doc/,出問題先看官網。

testng官網
安裝TestNG插件成功後,可以在設置面板上看到TestNG出現
preference面板

下載 Selenium Server

https://www.selenium.dev/downloads/ 官網下載 最新穩定版
selenium官網
我用的是3.141.59版本,點擊該版本這串數字,selenium-server-standalone-3.141.59.jar 被直接下載下來。

將 selenium-server-standalone-3.141.59.jar 放進Eclipse依賴

項目名 長按/右鍵 ,彈出菜單 Build Path -> Configure Build Path…
configure build path
Libraries功能區下 ,點擊 Add External JARs... 選擇 selenium-server-standalone-3.141.59.jar,點擊 Apply and Close
properties
可以看到 項目出現selenium jar依賴
referenced library

下載正確的ChromeDriver

Chrome瀏覽器輸入 chrome://settings/help ,查看Chrome版本
settings of chrome
要測試Chrome瀏覽器,不同的Chrome版本要用不同版本的chromedriver。
可以通過Taobao鏡像 https://npm.taobao.org/mirrors/chromedriver?spm=a2c6h.14029880.0.0.735975d7u7nsVM 下載對應版本的chromedriver。
一般chromedriver的版本號是和Chrome一致的。如果沒有找到,就下載稍低版本的chromedriver。
比如我用的是最新版Chrome 83.0.4103.61,找不到這個版本的chromedriver,我就下載83.0.4103.39的。
chromedriver
mirror index
下載對應系統的zip,然後解壓,放到指定文件夾。
在這裏插入圖片描述
我的路徑是 /Users/damon/temp/chromedriver/83.0.4103.39/chromedriver

編寫測試代碼

package com.automationtest;

import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AutoTest {
	
	@Test
	public static void test() throws InterruptedException {
		System.setProperty("webdriver.chrome.driver", "/Users/damon/temp/chromedriver/83.0.4103.39/chromedriver");  //這裏將指定版本的chromedriver可執行程序路徑 指定給 selenium識別
		
		WebDriver webdriver = new ChromeDriver() ;
		webdriver.get("https://www.baidu.com");//訪問Baidu
		
		Thread.sleep(3000);
		webdriver.findElement(By.id("kw")).sendKeys("莊達菲");
		Thread.sleep(3000);
		webdriver.findElement(By.id("su")).click();
		Thread.sleep(10000);
		
		webdriver.quit();//退出driver
		
	}

}

元素定位符可以用 開發者工具 F12/Fn+F12 打開查看
開發者工具
Eclipse 右鍵選擇 Run As TestNG Test 開始執行測試, Console出現

Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 2005
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
[1590068024.641][WARNING]: FromSockAddr failed on netmask
ChromeDriver was started successfully.

說明已經正常啓動chromedriver。

eclipse
測試通過。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章