|
先確保你的4444端口沒被占用,可以用netstat -an命令查看一下.
然后確保你的jdk版本在1.5以上.
第一步:
找到你下載的selenium解壓目錄下的selenium-server-0.9.2目錄.
在這個目錄下寫個批處理,內容為:
java -jar selenium-server.jar
保存為start.bat,名字隨便啦.雙擊啟動.這個是服務,在一切工作開始之前,
必須先啟動這個,啟動后的dos窗口不要關閉.
第二步:
在MyEclipse建個web工程,把selenium-java-client-driver-0.9.2目錄下的jar包加入
到web工程的lib目錄下.加入junit4支持.
第三步:
寫個測試index.jsp頁:
 <% @ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<html>
<head>
<title>test!</title>
</head>
<body>
<form action="success.jsp" method="post">
UserName:<input type="text" name="username" /><br />
<select name="select">
<option value="game">游戲</option>
<option value="program">編程</option>
</select> <br/>
<input type="submit" name="sub" value="submit"/> <br />
</form>
</body>
</html>

還有一個success.jsp:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>success</title>
</head>
<body>
ok!
</body>
</html>

寫個測試類:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;
import static org.junit.Assert.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;


public class TestPage
  {
private Selenium selenium;
@Before
public void setUp()
 {
//此url必須是Selenium服務器地址
String url = "http://localhost:4444";
selenium = new DefaultSelenium("localhost",SeleniumServer.getDefaultPort(),"*iexplore",url);
selenium.start();
}
@After
public void tearDown()
 {
try
 {
selenium.stop();
} catch (RuntimeException e)
 {
System.out.println(e.getMessage());
}
}
//測試標題,文本框輸入,及按鈕點擊
@Test
public void test1()
 {
//我這里是tomcat的地址,我的tomcat端口是8888,selenium是當前工程,我讓它打開首頁
selenium.open("http://localhost:8888/selenium/index.jsp");
String title = selenium.getTitle();
//原來網頁的標題
System.out.println(title);
selenium.type("xpath=//input[@name='username']", "zdw");
//得到輸入的文本框的值
System.out.println("textvalue:" + selenium.getValue("xpath=//input[@name='username']"));
selenium.click("xpath=//input[@name='sub']");
selenium.waitForPageToLoad("4000");
assertEquals(title, "test!");
//輸出新頁的標題
System.out.println(selenium.getTitle());
}
//測試選擇框
@Test
public void testSelect()
 {
selenium.open("http://localhost:8888/selenium/index.jsp");
selenium.select("xpath=//select[@name='select']", "index=1");
//得到選擇的id
System.out.println("selectid:" + selenium.getSelectedIndex("xpath=//select[@name='select']"));
//得到選擇的值
System.out.println("selectvalue:" + selenium.getSelectedValue("xpath=//select[@name='select']"));
selenium.click("xpath=//input[@type='submit']");
selenium.waitForPageToLoad("3000");
}
}










注釋已經很詳細了,感覺selenium很好用,完全可以模擬瀏覽器操作.我這里用的是ie,你當然可以用firefox或其它.
源碼可在我的網盤下載.
|