簡介
WatiN - Watir的.NET版:
Welcome at the WatiN (pronounced as What-in) website.Inspired by Watir developmentof WatiN started in December 2005 to make a similar kind of Web ApplicationTesting possible for the .Net languages. Since then WatiN has grown into aneasy to use, feature rich and stable framework. WatiN is developed in C# andaims to bring you an easy way to automate your tests with InternetExplorer and FireFox using .Net.
目前最新版本:WatiN2.0 RC 1
http://watin.sourceforge.net/releasenotes-2-0-20-1089.html
支持的測試環境:
|
Windows XP |
Windows Vista |
Windows 2003 |
Windows 2008 |
IE 6 |
OK |
- |
- |
- |
IE 7 |
OK |
- |
- |
OK |
IE 8 |
OK |
- |
- |
- |
Firefox 2 |
OK |
- |
- |
- |
Firefox 3 |
OK |
- |
- |
OK |
WatiN 的腳本錄製器 - WatiN Test Recorder:
http://watintestrecord.sourceforge.net/
2.0 beta版本需要IE7以上
WatiN vs. Selenium RC
Item |
WatiN |
Selenium RC |
Explorer Supported |
Known work Ø IE 6 and IE 7 |
Known work Ø IE 6 and IE 7 Ø Firefox 1.5.0 and 2.0 Ø Opera 8.5.4 and 9.0.2 Should work Ø Firefox 0.8 to 2.0 Ø Mozilla Suite 1.6+, 1.7+ Ø Sea monkey 1.0 |
System supported |
Known work Ø Windows XP and 2003 |
Known work Ø Windows XP and 2003 Ø Windows 2000(need to install install reg.exein order to use IE) Ø Mac OS X Ø Linux |
Language supported |
Ø C# |
Ø C# Ø Java Ø Perl Ø PHP Ø Python Ø Ruby |
Test environment supported |
Ø Visual Studio 2005 Team System |
Ø Visual Studio 2005 Team System |
AJAX |
Supports AJAX website testing |
l Selenium Server communicates directly with the browser using AJAX (XmlHttpRequest) l The Selenium Server is great for testing complex AJAX-based web user interfaces under a Continuous Integration system |
Get/Post requests |
|
We can send commands directly to the Server using simple HTTP GET/POST requests |
Https supported |
|
Support for https |
Javascrīpt Supported |
Void Document.Runscrīpt(string) |
l We can write selenium RC tests in Javascrīpt with JsUnit. l it Allows a Selenium-enabled browser to run Javascrīpt on arbitrary websites. |
HTML |
Automates all major HTML elements and find elements by multiple attributes |
|
HTML dialogs |
Supports HTML dialogs (modal and modeless) |
|
Frame |
Supports frame (Cross domain) and iframes |
|
Popup dialogs |
Supports popup dialogs like alert, confirm, login etc |
|
Screenshots |
Support creating screenshots of web pages |
|
|
|
對現有控件的兼容性不好。比如文件上傳控件和日曆控件就無法在Selenium RC中捕捉 http://bbs.51testing.com/thread-84131-1-6.html |
Developing Info
Item |
WatiN |
Selenium RC |
Developing Language |
Ø C# |
Ø Java and so on |
Methods Example
Item |
WatiN Example |
Selenium RC Example |
Set element event |
Document.button(Find.ById(btnG”)).click() |
DefaultSelenium.Type(“q”,”hello world”) |
Get element attributes |
Document.button (Find.ById(btnG”)).Style. Height |
DefaultSelenium.GetElementHeight(“q”) |
especial methods |
Then we can’t hanle the time used for pages loading. ===》
Ø Link[1].Click() Ø Link(Find.ByIndex(1)).Click() We can use these two methods to click the links that the value is null. |
Ø WaitForPageToLoad(“5000”) (if we want to go to another page and get the elements in the new page, we have to use the method, or we will in the old page.)
《== We can’t find the links that the value is null |
WatiN測試Google的例子
using System;
using System.Collections.Generic;
using System.Text;
using WatiN.Core;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
staticvoid Main(string[]args)
{
//Open a new Internet Explorer window and
//goto the google website.
IEie = new IE("http://www.google.com.hk", true);
// Find thesearch text field and type Watin in it.
ie.TextField(Find.ByName("q")).TypeText("WatiN");
//Click the Google search button.
ie.Button(Find.ByValue("Google 搜索")).Click();
//Uncomment the following line if you want to close
//Internet Explorer and the console window immediately.
//ie.Close();
}
}
}
獲取頁面元素內容:
//Open an new Internet Explorer Window and
//goto the google website.
IEie = new IE("http://www.google.com.hk",true);
//Find the search text field and type Watin in it.
ie.TextField(Find.ByName("q")).TypeText("WatiN");
//Click the Google search button.
ie.Button(Find.ByValue("Google 搜索")).Click();
//Find the table cell which shows the search result statistics.
Elementelement = ie.Element(Find.By("id", "resultStats"));
stringresultStats = element.Text;
//Write these statistics to the console window.
Console.WriteLine(resultStats);
//Uncomment the following line if you want to close
//Internet Explorer and the console window immediately.
//ie.Close();
參考:
Getting started with WatiN
http://watin.sourceforge.net/gettingstarted.html
WatiN and Thread.ApartmentState
http://watin.sourceforge.net/apartmentstateinfo.html
WatiN支持的頁面元素
Html element |
WatiN Class |
WatiN Collection |
Example |
Version |
|
|
|
|
|
<a /> |
Link |
LinkCollection |
Ie.Link(linkId) |
0.7 |
<area /> |
Area |
AreaCollection |
ie.Area(Find.ByAlt(alttext)) |
1.2 |
<button /> |
Button |
ButtonCollection |
Ie.Button(buttonId) |
0.9 |
<div /> |
Div |
DivCollection |
Ie.Div(divId) |
0.7 |
<form /> |
Form |
FormCollection |
Ie.Form(formId) |
0.7 |
<frame /> |
Frame |
FrameCollection |
Ie.Frame(frameId) |
0.7 |
<frameset /> |
- |
FrameCollection |
Ie.Frames |
0.7 |
<iframe /> |
Frame |
FrameCollection |
Ie.Frame(iframeId) |
0.9 |
<img /> |
Image |
ImageCollection |
Ie.Image(imageId) |
0.7 |
<input type=button/> |
Button |
ButtonCollection |
Ie.Button(buttonId) |
0.7 |
<input type=checkbox/> |
CheckBox |
CheckBoxCollection |
Ie.CheckBox(checkboxId) |
0.7 |
<input type=file/> |
FileUpload |
FileUploadCollection |
Ie.FileUpload(fileuploadId) |
0.9 |
<input type=hidden/> |
TextField |
TextFieldCollection |
Ie.TextField(hiddenId) |
0.7 |
|
|
|
|
no longer supported as of 2.0 beta 1 |
<input type=image/> |
Image |
ImageCollection |
Ie.Image(imageId) |
0.9.5 |
<input type=password/> |
TextField |
TextFieldCollection |
Ie.TextField(passwordId) |
0.7 |
<input type=radio/> |
RadioButton |
RadioButtonCollection |
Ie.RadioButton(radioId) |
0.7 |
<input type=reset/> |
Button |
ButtonCollection |
Ie.Button(resetId) |
0.7 |
<input type=submit/> |
Button |
ButtonCollection |
Ie.Button(submitId) |
0.7 |
<input type=text/> |
TextField |
TextFieldCollection |
Ie.TextField(textId) |
0.7 |
<label /> |
Label |
LabelCollection |
Ie.Label(elementId) |
0.7 |
<option /> |
Option |
OptionCollection |
Ie.Select(selectId).Options |
1.0 |
<p /> |
Para |
ParaCollection |
Ie.Para(pId) |
0.7 |
<select /> |
Select |
SelectCollection |
Ie.Select(selectId) |
0.7 |
<span /> |
Span |
SpanCollection |
Ie.Span(spanId) |
0.7 |
<table /> |
Table |
TableCollection |
Ie.Table(tableId) |
0.7 |
<tbody /> |
TableBody |
TableBodyCollection |
Ie.TableBody(tablebodyId) Ie.Table(tableid).TableBodies |
1.0 |
<td /> |
TableCell |
TableCellCollection |
Ie.TableCell(tablecellId) or Ie.Table(TableId).TableRows[0].TableCells[0] |
0.7 |
<textarea /> |
TextField |
TextFieldCollection |
Ie.TextField(textareaId) |
0.7 |
<tr /> |
TableRow |
TableRows |
Ie.TableRow(tablerowId) or Ie.Table(TableId).TableRows[0] |
0.7 |
All elements, also the ones not mentioned in this list |
Element and ElementsContainer |
ElementCollection |
Ie.Element(elementId) Ie.Element(tagname, elementId) |
0.9
1.2 |
HTML Mapping Table
http://watin.sourceforge.net/htmlelementmapping.html
WatiN中所有的控件以及控件的識別方法
在WatiN的源代碼中可以看到所有的控件識別設計類都是在繼承了與element相關的類
包括Element,ElementAttributeBag, ElementCollection, ElementContainer, ElementSupport,ElementTag。
首先來看Element的類可以看到它繼承IAttributeBag類,在Elemental類中寫到的方法有:
1. Classname: Get the name of thestylesheet class assigned to this element;得到傳輸給此控件默認格式類的名稱。返回值爲string.
2. Complete: Boolean Value, Get a valueindicating whether the element is completely loaded;得到一個波爾值,查看是否此對當前控件的操作完全加載。返回值爲波爾值.
3. Enabled: Get a Value indicating whetherthis element is enabled.得到一個波爾值來確認當前的控件是否是可用的.返回值爲波爾值.
4. ID: Get the if of this element asspecified in the HTML ,返回當前控件在此HTML頁面中的識別ID, 返回值爲string。
5.TEXT: Get the inner text of thiselement(or all the inner text of all the elements contained in this elment). 返回當前控件中的文本,或者是返回當前控件所包含的控件中的所有文本,返回值爲string.
6.TextBefore: Returns the text displayedbefore this element when it’s wrapped in a Label element, otherwise it returns null. 返回當前控件前面的Label的文本內容,如果當前控件前面的控件不是Label則返回null, 返回值爲string.
7. InnerHtml: Gets the inner HTML of thiselement. 返回當前控件的內部HTML代碼。返回值不用說當然爲string.
8. OuterText: Gets the outer text, 返回外部文檔,返回值爲string.
Shit,這個控件我還真不知道怎麼用,呵呵。查了一下解釋如下:
InnerText:不包括標誌,標誌以內的純文本
OuterText:包括標誌,連標記及標誌內的文本
InnerHtml:不包括標誌,標誌以內的Html內容
OuterHtml:包括標誌,連標記及標誌內的Html內容
9. TagName: Gets the tag name of thiselement 返回當前控件的標籤。返回值爲string.
10. Title: Get the title. 返回當前頁面的標題。返回值爲stieng.
11. NextSibling: Gets the next sibling ofthis element in the Dom of the HTML page.返回當前標籤在此HTML頁面Dom控件中的下一個兄弟控件。返回值爲控件即(element)
12. PreviousSibling: Gets the previoussibling of this element in the Dom of the HTML page. 返回當前標籤在此HTML頁面Dom控件中的下一個兄弟控件,返回值爲控件即(element)。
13. Parent: Gets the parent element of thiselement, If the parent type is known you can cast it to that type. 返回當前控件的父級控件,如果父級的控件類型知道,可以定義一個和父級同類型的變量控件。返回類型爲控件(element).這個比較難理解,下面是舉例:
Div
a id="watinlink" href="http://watin.sourceforge.net"/
ahref="http://sourceforge.net/projects/watin" /
Div
上面的HTML所示第二個超鏈接沒有id,如何點擊它來實現超鏈接?這時可以使用Parent這個方法:
首先定義一個變量Div,然後把這兩個超鏈接所在的div賦值給這個Division變量。
DivwatinDiv = ie.Link(“watinlink”).Parent;
然後去找第二個Link, 可以把第一個Link看做是Links[0],那麼第二個Link就是Link[1]
watinDiv.Links[1].Click();
14.Style: Style is the element’s style, 返回當前控件的格式。返回類型爲Style.
15.GetAttributeValue: This method can beused is the attribute is not available as a property of the element of asubclass of the element. Need a parameter’attributeName’, this parameter shouldbe the name of the property exposed by IE on it’s element object. The return isthe value of the attribute if available, otherwise null is returned. 當控件的屬性不存在或者或者屬性屬於此控件的一個子類時此方法可以使用。但是需要傳遞給此方法一個參數即屬性名稱(它應該是被IE暴露的一個空間實體),返回值爲控件的屬性值或者爲null.
16. ToString: Returns a string thatrepresents the current object, or null.返回代表當前實體的值,如果沒有則返回空。返回類型爲string.
17.Click: Click this element and waits tillthe event is completely finished(Page is loaded and ready). 點擊當前控件然後等待,知道整個事件完成即:頁面被完全加載。無返回值.
18.ClickNoWait: Click this instance andreturns immediately. Use this method when you want to continue without waitingfor the click event to be finished. Mostly used when a HTML Dialog is displayedafter clicking the element. 觸發事件並立刻返回信息然後去判斷需要如何執行,通常是在點擊或者跳轉頁面還沒完成時你需要其它操作。一般情況下是在當彈出對話框時使用這個方法。無返回值。
19.Focus: Gives the input focus to thiselement. 聚焦在當前這個輸入控件,我不是很明白這個方法。無返回值。
20.DoubleClick: Doubleclicks this element. 雙擊當前的控件。無返回值。
21.KeyDown, KeyPress, KeyUp 三個方法分別爲按下鍵盤不放, 按一下鍵盤,和鬆開按鍵盤。很繞口. 這個應該是從.Net繼承的。
22. Blur: Fires the blur event on thiselement. 這個應該是和focus相反的方法。取消對這個控件的focus.
QTP + WatiN
Set IE =DotNetFactory.CreateInstance("WatiN.Core.IE","C:\Documents andSettings\Administrator\桌面\WatiN-2.0.10.928-net-2.0\WatiN-2.0.10.928-net-2.0\bin\WatiN.Core.dll")
SetFind=DotNetFactory.CreateInstance("WatiN.Core.Find","C:\Documentsand Settings\Administrator\桌面\WatiN-2.0.10.928-net-2.0\WatiN-2.0.10.928-net-2.0\bin\WatiN.Core.dll")
IE.GoTo("http://www.zbitedu.com")
IE.WaitForComplete
IE.TextField(Find.ByName("searchkey")).TypeText("vbs測試webservice")
IE.Button(Find.ByName("subjectsearch")).Click()
Set IEpage = IE.AttachToIE(Find.ByUrl("http://www.zbitedu..com"))
Set LinkObj = IEpage. Link(Find.ByUrl("http://www.zbitedu.com/)
IF LinkObj.Exists Then
LinkObj.Click()
' IE.AttachToIE(Find.ByUrl("http://www.zbiteducom)
Set ConsoleObj=DotNetFactory.CreateInstance("System.Console","System")
Consoleobj.Write("PASS")
' Msgbox("PASS")
else
Msgbox("FAILL")
End If
IE.Close
IEpage.Close
IE.AttachToIE(Find.ByUrl("http://www.zbitedu.com).Close
WatiN中常用的類
WatiN.Core.Find
最普遍使用的類就是Find類的,它是一個工廠類,主要使用它的靜態方法來實現一些查詢條件。比如像上面的例子中的這個語句“ie.Button(Find.ByName("btnG")).Click();”就調用了Find的靜態方法ByName來查詢一個name屬性爲指定值的HTML元素,然後再調用IE對象的Button方法把這個元素轉換爲按鈕對象。
WatiN.Core.IE
這應該是最關鍵的類了。他常用的方法是和屬性爲
屬性
HtmlDialogs 返回當前對象用JavaScript打開的模式窗口(需然幫助文檔中說非模式窗口也包括在內,但在試用中發現用window.open打開的窗口沒有被)
Frames 返回當前的象裏的所有Frames
方法
靜態方法 AttachToIE 與一個已經找開的IE關連。
Button,TextField,Image,Div 等一系列方法。與Find對象共同使用用於返回IE中特定的按鈕,輸入框,等HTML元素。
WatiN應用中的一些技巧
1、如何去捕獲一個新彈出的窗口。
背景:有些鏈接是從一個新彈出的窗口中打開的,我如果關連上這類型的窗口。
方案:下面以一個具體例子爲例。系統中有一個登陸界面:login.aspx 登陸成功能後會調用JAVASCRIPT的window.open方法打開系統的主窗口,然後關閉當前這個窗login.aspx。
剛開始時,我的代碼是這樣寫的
public void Login(string uid, stringpasswd)
{
string url = Host +"login.aspx";
ie = new IE();
ie.GoTo(url);
ie.WaitForComplete();
ie.TextField(Find.ById("txtUserName")).Value= uid;
ie.TextField(Find.ById("txtPwd")).Value = passwd;
ie.Button(Find.ById("btnLogin")).Click;//注意這裏,我每次執行到這裏都出錯。下面會說明原因。
ie =IE.AttachToIE(Find.ByTitle(new WatiN.Core.Comparers.RegexComparer(newSystem.Text.RegularExpressions.Regex(".*綜合信息系統.*"))));
ie.WaitForComplete();
MainFrame =ie.Frame(Find.ByName("MainFrame_00001"));
MenuFrame =ie.Frame(Find.ById("leftMenu"));
}
看到上面的註譯沒有?那麼執行完後WatiN都會出現一個等待完成超時的異常,這是因爲點擊了登陸按鈕後,如果登陸成功的話,系統已經把這個窗口關閉了,因爲它根本不可能完成。呵呵~~```所以要修改一下。
public void Login(string uid, stringpasswd)
{
string url = Host +"frmlogon.aspx";
ie = new IE();
ie.GoTo(url);
ie.WaitForComplete();
ie.TextField(Find.ById("txtUserName")).Value = uid;
ie.TextField(Find.ById("txtPwd")).Value = passwd;
ie.Button(Find.ById("btnLogin")).ClickNoWait();//這個方法改成這樣,那點擊後就不會等代碼IE完成了。
//下面這句就是處理登陸的技巧所在,系統打開了另一個窗口。
//下面這句就是用正則表達式捕獲這個窗口。
ie =IE.AttachToIE(Find.ByTitle(new WatiN.Core.Comparers.RegexComparer(newSystem.Text.RegularExpressions.Regex(".*綜合信息系統.*"))));
ie.WaitForComplete();
MainFrame = ie.Frame(Find.ByName("MainFrame_00001"));
MenuFrame =ie.Frame(Find.ById("leftMenu"));//把系統裏的Frame先保存下來。
}
2、對於alert 、confirm 等javascript彈出的窗口的捕獲。
背景:一個系統經常會使用以上這些javascript來彈出一些提示信息,如果捕獲這些窗口,並模擬用戶點擊這些窗口上的OK或Cancel按鈕?
方案:其實WatiN在默認情況下,都會自動地去點擊這些彈出式窗口上的Cancel按鈕的,但如果用戶要明確點擊哪些事件的話可以對IE對象增加一個“查看器”()
//錯誤事例
protected void f()
{
WatiN.Core.DialogHandlers.ConfirmDialogHandler dh = newWatiN.Core.DialogHandlers.ConfirmDialogHandler();
ie.AddDialogHandler(dh);//這句增加了一個控制器
/**/
/*
假設yzp_dic_btn_cls這個按鈕的onclick事件會用JS彈出一個Confirm窗口。
錯誤,測會在這裏彈出一個窗口,然後等待用戶進行操作(隨便點擊一個按鈕才繼續執行)
然後因爲用戶已經點擊了按鈕關閉 彈出窗口。下一句的dh.WaitUntilExists(3);將會超時,拋出異常
*/
doc.Button(Find.ByName("yzp_dic_btn_cls")).Click();
dh.WaitUntilExists(3);//等待彈出窗口的出來。最多等三秒。
dh.OKButton.Click();//點擊這個窗口的OK按鈕
ie.RemoveDialogHandler(dh);
doc.Button(Find.ByName("btn_close")).Click();
}
正確的示例應該是:
protected void f()
{
WatiN.Core.DialogHandlers.ConfirmDialogHandler dh = newWatiN.Core.DialogHandlers.ConfirmDialogHandler();
ie.AddDialogHandler(dh);
doc.Button(Find.ByName("yzp_dic_btn_cls")).ClickNoWait();//把原來的Click改成這個方法。
dh.WaitUntilExists(3);//等待彈出窗口的出來。最多等三秒。
dh.OKButton.Click();//點擊這個窗口的OK按鈕
ie.RemoveDialogHandler(dh);
doc.Button(Find.ByName("btn_close")).Click();
}
3、關於用JS彈出的Modal窗口(模式窗口)的處理.
背景:有些地方需要彈出模式窗口來處理數據。
方解:當點擊了彈出模式窗口的按鈕或連接後馬上用IE對像的HtmlDialogs屬生來獲取模式窗口。
protected void f()
{
//假設下面這行代碼會彈出一個模式窗口把原來的Click改成這個方法。
//記住這裏要用ClickNoWait而不能用Click,否則在模式窗口關閉之前代碼不會繼續執行。
ie.Button(Find.ByName("yzp_dic_btn_cls")).ClickNoWait();
ie.HtmlDialogs[ie.HtmlDialogs.Length -1].TextField(Find.ByName("Q")).Value = "Hello";
ie.HtmlDialogs[ie.HtmlDialogs.Length -1].Button(Find.ByName("btn_query")).Click();
}
WatiN插件 – QAliber
http://www.qaliber.net/Wiki/index.php?title=WatinN_Plug-in
Qaliber主頁:
作者:BennyCohen
包括兩個版本,其中QAliberTest Developer版本作爲VS.NET的插件使用:
QAliber Test Developer (free open source) is a VisualStudio plug-in.
Create test cases as an integral part of yourdevelopment solution.
QAliber Test Builder (free open source) is a robust testingframework for creating and executing tests with no coding skills.
TestAndTry.com對這款工具的評價是“VeryFast GUI Automation With Free QAliber”:
http://www.testandtry.com/2010/03/04/very-fast-gui-automation-with-free-qaliber/
主要特點:
Create test cases as an integral part of yourdevelopment solution.
Create GUI / API level test quick!
Record / Play GUI automation.
Supports Win32 / .NET forms / WPF / WEB GUI testing.
Run on all windows platforms with .NET framework 3.0and up (XP,Vista,Win 7)
Write C#/VB.net code, use the .NET frameworkcapabilities.
下載地址:
http://sourceforge.net/projects/qaliber/files/