Selenium 是 ThoughtWorks 專門為 Web 應用程序編寫的一個驗收測試工具。據 Selenium 主頁所說,與其他測試工具相比,使用 Selenium 的最大好處是:
Selenium 測試直接在瀏覽器中運行,就像真實用戶所做的一樣。Selenium 測試可以在 Windows、Linux 和 MacintoshAnd 上的 Internet Explorer、Mozilla 和 Firefox 中運行。其他測試工具都不能覆蓋如此多的平臺。
使用 Selenium 和在瀏覽器中運行測試還有很多其他好處。下面是主要的兩大好處:
- 通過編寫模仿用戶操作的 Selenium 測試腳本,可以從終端用戶的角度來測試應用程序。
- 通過在不同瀏覽器中運行測試,更容易發現瀏覽器的不兼容性。
Selenium 的核心,也稱 browser bot ,是用 JavaScript 編寫的。這使得測試腳本可以在受支持的瀏覽器中運行。browser bot 負責執行從測試腳本接收到的命令,測試腳本要么是用 HTML 的表布局編寫的,要么是使用一種受支持的編程語言編寫的。
在下面的情況下,可以選擇SeleniumRC進行功能測試。
- condition statements
- iteration
- logging and reporting of test results
- error handling, particularly unexpected errors
- database testing
- test case grouping
- re-execution of failed tests
- test case dependency
- screenshot capture of test failures
首先要下載SeleniumRC,不用安裝,解壓即可,可以看到這樣幾個目錄,下圖示:
selenium-server-1.0.1目錄,是服務器端,他可以接受測試程序指令,并將測試結果返回測試程序。
在測試前必須先啟動他,啟動過程:開始-運行-cmd-cd <服務器端目錄>-java -jar selenium-server.jar
(服務器端其實就是個Jar文件)
?
然后就可以進行客戶端,本文用C#來進行測試,首先建立一個C#類庫工程,添加引用selenium-dotnet-client-driver-1.0.1目錄下的所有DLL,具體如下圖示。
下面,新建類SeleniumTest,具體代碼如下:
?

1 [TestFixture]
2 public class SeleniumTest
3 {
4 private ISelenium selenium;
5 private StringBuilder verificationErrors;
6
7 [SetUp]
8 public void SetupTest()
9 {
10 selenium = new DefaultSelenium( " localhost " , 4444 , " *iexplore " , " http://localhost:2896/WebTestSite/ " );
11 selenium.Start();
12
13 verificationErrors = new StringBuilder();
14 }
15
16 [TearDown]
17 public void TeardownTest()
18 {
19 try
20 {
21 selenium.Stop();
22 }
23 catch (Exception)
24 {
25 // Ignore errors if unable to close the browser
26 ? }
27 Assert.AreEqual( "" , verificationErrors.ToString());
28 }
29
30 [Test]
31 public void TheSeleniumTest()
32 {
33 selenium.Open( " /WebTestSite/ " );
34 selenium.Type( " TextBox1 " , " qeq " );
35 selenium.Type( " TextBox2 " , " qwe " );
36 selenium.Click( " Button1 " );
37
38 // 判斷是否出現alert("fail")
39 ? Assert.AreEqual( " fail " , selenium.GetAlert());
40
41 selenium.Type( " TextBox1 " , " 123 " );
42 selenium.Type( " TextBox2 " , " 123 " );
43 selenium.Click( " Button1 " );
44 Assert.AreEqual( " fail " , selenium.GetAlert());
45
46 // 點擊鏈接
47 ? selenium.Click( " link=2 " );
48 // 等待
49 ? selenium.WaitForPageToLoad( " 30000 " );
50 selenium.Click( " link=3 " );
51 selenium.WaitForPageToLoad( " 30000 " );
52
53 }
54 [Test]
55 public void TestTitle()
56 {
57 selenium.Open( " /WebTestSite/**.aspx " );
58 Assert.AreEqual( " yourtitle " , selenium.GetTitle());
59
60 }
61 }
?
這樣,就建好了,可以打開NUit進行測試,也可以直接寫個main進行測試。
?
seleniumhq官方文檔:
http://seleniumhq.org/docs/05_selenium_rc.html#introduction
?
參考:
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
