Selenium快速入门.docx
《Selenium快速入门.docx》由会员分享,可在线阅读,更多相关《Selenium快速入门.docx(14页珍藏版)》请在冰点文库上搜索。
Selenium快速入门
Selenium快速入门
Seleniumisasuite.[swi:
t]oftoolstoautomatewebbrowsersacrossmanyplatforms.
Seleniumrunsinmanybrowsersandoperatingsystems.Seleniumcanbecontrolledbymanyprogramminglanguagesandtestingframeworks.
严格说来,Selenium是一套完整的Web应用程序测试系统,它包含了SeleniumCore、测试的录制(SeleniumIDE)、编写及运行(SeleniumRemoteControl)和测试的并行处理(SeleniumGrid)。
1)Selenium的核心SeleniumCore基于JsUnit,完全由JavaScript编写,因此可运行于任何支持JavaScript的浏览器上。
SeleniumCore由一种指定格式的HTML文件驱动,在一定程度上增强了测试套件(TestSuite)的可读性。
SeleniumCore支持DHTML的测试案例,它是SeleniumIDE和SeleniumRC的引擎.
2)SeleniumIDE是FireFox的一个插件,支持脚本录制.SeleniumIDE仅支持Firefox流览器,仅支持selenium语言.
3)SeleniumRemoteControl允许测试人员使用常见的语言(自然包括C#等.NET语言)编写测试代码,并支持不同操作系统(Windows,Linux,Mac)下的各种主流浏览器(Firefox2以上,safari2以上,IE6以上,Opera8以上,googlechrome,others)。
4)SeleniumGrid的作用是将测试分发至多台机器,允许同时并行地、在不同的环境上运行多个测试任务,这样便可大大加快测试速度。
与WatiN相同,Selenium也是一款同样使用ApacheLicense2.0协议发布的开源框架。
SeleniumGridtakesSeleniumRemoteControltoanotherlevelbyrunningtestsonmanyserversatthesametime,cuttingdownonthetimeittakestotestmultiplebrowsersoroperatingsystems.
一、SeleniumIDE
SeleniumIDEisaFirefoxadd-onthatmakesiteasytorecordandplaybacktestsinFirefox2+.YoucanevenuseitgeneratecodetorunthetestswithSeleniumRemoteControl.
SeleniumIDEisanintegrateddevelopmentenvironmentforSeleniumscripts.ItisimplementedasaFirefoxextension,andallowsyoutorecord,edit,anddebugtests.SeleniumIDEincludestheentireSeleniumCore,allowingyoutoeasilyandquicklyrecordandplaybacktestsintheactualenvironmentthattheywillrun.
SeleniumIDE是基于FIREFOX浏览器的一个插件(提供GUI界面来运行Selenium测试),提供脚本录制功能及脚本转换(可以将用户在浏览器中执行的操作记录下来,生成各种形式的脚本,可以将这些脚本保存供以后使用)(IE下可以使用SeleniumCore+IEDevelperToolBar)。
FIREFOX浏览器,在工具菜条下应该就可以看到SeleniumIDE菜单项;ClickingFirebug(GotoFirefoxTools)orpressF12canopentheFirebugdebugtool.
每个脚本都是由一条条的Action(行为)组成,而每个Action又由(Command,Target,Value)三者组成。
Command就是SeleniumAPI提到的内容;Target指的是Web中的某个对象,比如:
文字,输入框等,如果选取对象呢?
这就用到了XPath;而Value就是这个对象的值。
开始Selenium的脚本录制,右上角有个红色的圆点,当它下按时(如上图)就表示IDE正在进行脚本录制.开始录制的时候,直接操作Firefox浏览器窗口就可以了,IDE会自动记录你的操作.
重新回放脚本:
在运行脚本后,你会发现IDE表格的颜色发生了变化,运行前,脚本表格为白色,成功运行完毕后;表格为青色,其中还分为深青色和浅青色两种,浅青色表示:
动作成功,如:
打开网页成功,点击按钮成功等等,而深青色表示:
判断正确;出错时,表格可能会出现两种颜色,一种是浅粉红色,一种是深粉红色。
浅粉红色表示判断结果为false,这种情况案例还是会继续执行下去,判断的失败不会影响案例的运行,深粉红色表示动作失败.
Selenium录制工具根据id属性定位html元素;selinum使用xpath和css等选择html元素。
SeleniumIDE还有一个重要的功能就是把脚本的转换,option->clipboardFormat->Java/JUnit4/WebDriver.
Selenium可以生成7种语言的脚本:
html,java,C#,ruby,python,perl,php。
这种功能是使用.js文件实现的。
Selenium不同于一般的测试工具。
Selenium的脚本录制工具是通过监听用户对html页面的操作来录制脚本的。
SeleniumServer通过向浏览器发出调用JavaScript实现对Html页面的全面追踪,并通过网络把执行结果返回给Selenium客户端。
一般的脚本测试工具录制脚本,实际上都是通过拦截浏览器收发的http请求来实现的,事实上并没有办法录制用户对html页面的操作。
如WebLoad,LoadRunner都是只记录http请求,不能真正记录对页面的操作。
二、Selenium-RC是selenium-remotecontrol缩写,是使用具体的语言来编写测试类。
SeleniumRemoteControlisaclient/serversystemthatallowsyoutocontrolwebbrowserslocallyoronothercomputers,usingalmostanyprogramminglanguageandtestingframework.
SeleniumRCisatesttoolthatallowsyoutowriteautomatedwebapplicationUItestsinanyprogramminglanguageagainstanyHTTPwebsiteusinganymainstreamJavaScript-enabledbrowser.
1SeleniumRCcomesintwoparts.
1)Aserverwhichautomaticallylaunchesandkillsbrowsers,andactsasaHTTPproxyforwebrequestsfromthem.
2)Clientlibrariesforyourfavoritecomputerlanguage.
SeleniumRC主要由两部分组成:
1).SeleniumServer:
SeleniumServer负责控制浏览器行为,总的来说,SeleniumServer主要包括3个部分:
Launcher,HttpProxy,SeleniumCore。
其中SeleniumCore是被SeleniumServer嵌入到浏览器页面中的。
其实SeleniumCore就是一堆JS函数的集合,就是通过这些JS函数,我们才可以实现用程序对浏览器进行操作。
2).ClientLibraries:
写测试案例时用来控制SeleniumServer的库。
2准备工作:
(1)下载selenium了,到http:
//www.openqa.org/selenium/下载就可以了,记得选择selenium-rc的版本.
(2)学习一下xpath的知识。
有个教程:
http:
//www.zvon.org/xxl/XPathTutorial/General_chi/examples.html
(3)安装jdk1.5
3selenium-rc使用方法,SeleniumJava测试
1)java项目中,加入selenium-java-client-driver.jar。
2)启动selenium-remote-control服务器:
SeleniumServer是用JAVA实现的,相应的库文件在HOME/server/selenium-server.jar。
运行如下代码从命令行启动:
java代码:
java-jarselunium-server.jar
3)把SeleniumIDE录制的Selenium脚本转换成Java格式,Java代码复制到Java项目中。
4SeleniumRC运行机制
⏹程序语言通过调用clientdriver来发出浏览器操作指令(例如打开制定url),由clientdriver把指令传递给SeleniumServer解析。
SeleniumServer负责接收、解析、执行客户端执行的Selenium指令,转换成各种浏览器的命令,然后调用相应的浏览器API来完成实际的浏览器操作。
⏹我们所编写的测试案例,其实是通过发送Http请求实现对SeleniumServer的控制.
SeleniumServer实际充当了客户端程序与浏览器间httpproxy。
1).测试案例(Testcase)通过ClientLib的接口向SeleniumServer发送Http请求,要求和SeleniumServer建立连接。
(2).SeleniumServer的Launcher启动浏览器,把SeleniumCore加载入浏览器页面当中,并把浏览器的代理设置为SeleniumServer的HttpProxy。
(3).测试案例通过ClientLib的接口向SeleniumServer发送Http请求,SeleniumServer对请求进行解析,然后通过HttpProxy发送JS命令通知SeleniumCore执行操作浏览器的动作。
(4).SeleniumCore接收到指令后,执行操作。
(5).浏览器收到新的页面请求信息(因为在(4)中,SeleniumCore的操作可能引发新的页面请求),于是发送Http请求,请求新的Web页面。
由于SeleniumServer在启动浏览器时做了手脚,所以SeleniumServer会接收到所有由它启动的浏览器发送的请求。
(6).SeleniumServer接收到浏览器的发送的Http请求后,自己重组Http请求,获取对应的Web页面。
(7).SeleniumServer的HttpProxy把接收的Web页面返回给浏览器。
5为什么SeleniumRC中的SeleniumServer需要以这种代理服务器的形式存在?
其实,这和浏览器的“同源策略”(TheSameOriginPolicy)有关。
所谓同源,就是指域名、协议、端口相同。
同源策略,一个阻止跨网站脚本访问的安全策略。
它是由Netscape提出的一个著名的安全策略,现在所有可支持javascript的浏览器都会使用这个策略,一个阻止进行跨网站脚本访问的安全策略。
比如说,浏览器的两个tab页中分别打开了tab1和tab2同源的脚本才能被执行,所以,tab1只能执行JavaScript1和JavaScript3脚本,而JavaScript2不能执行,从而防止其他网页对本网页的非法篡改。
因为SeleniumCore的JS脚本的“源”是localhost,所以浏览器会阻止SeleniumCore的JS脚本在测试页面上执行(如果只使用SeleniumCore进行测试,需要把SeleniumCore安装到远程服务器上)。
为了解决这个问题,SeleniumRC中的SeleniumServer就以代理服务器的形式存在,通过修改WebSite的源信息,从而达到欺骗浏览器的目的,就这样,SeleniumRC就轻松绕过了同源策略。
浏览器会认为WebSite和SeleniumCore来自同一个“源”----代理服务器!
四、编写测试用例
需要的JAR:
selenium-java-client-driver.jar;junit
编写一个JUNIT的单元测试,要构建一个Selenium,包括如下步骤:
*构建一个Selenium实例
*启动Selenium实例
*执行Selenium命令,并验证结果。
*关闭Selenium实例
HowtoIntegrateEclipsewithSelenium?
1ImportSeleniumPackagetoLibrary
1)LaunchEclipse
2)NewaJavaProjectandthenclickFinish
3)Rightclickproject->Properties->JavaBuildPath->AddLibrary->JUnit->JUnit4
2ImportSeleniumclientandserver,LoadSeleniumpackage
1)RightclicktheprojectBuildPathLinkSourceAddtoBuildPath.
2)Inthedialog,clickBrowsertochoosethefolderwheretheseleniumclientandserverare.AndthenclickFinish.(selenium-java-2.26.0.jar,selenium-server-standalone-2.26.0.jar)
3)Afteraddingtheclientandserverjarfilestobuildpath,youcouldfindtheyareunderReferencedLibraries
Tillnow,thesettingisfinished.
DefaultSelenium的构造器的参数是你连接的Selenium服务器的ip地址和端口,第三个参数是用来执行Selenium指令的浏览器,最后一个参数是浏览器的起始URL。
如下是一个示例,用来测试Selenium"
1.packagecom.thoughtworks.selenium;
2.
3.importjunit.framework.*;
4.
5.importorg.openqa.selenium.server.*;
6.
7.publicclassGoogleTestextendsTestCase
8.{
9. privateSeleniumselenium;
10.
11. publicvoidsetUp()throwsException{
12. Stringurl="";
13. selenium=newDefaultSelenium("localhost",SeleniumServer.getDefaultPort(),"*firefox",url);
14. selenium.start();
15. }
16.
17. protectedvoidtearDown()throwsException{
18. selenium.stop();
19. }
20.
21. publicvoidtestGoogleTestSearch()throwsThrowable{
22. selenium.open("/intl/zh-CN/");
23. selenium.type("q","selenium");
24. selenium.click("btnG");
25. selenium.waitForPageToLoad("30000");
26. assertEquals("selenium-Google搜索",selenium.getTitle());
27.
28. }
29.
30.}
五、多环境测试
packagetest;
importorg.junit.Test;
importjunit.framework.TestCase;
importcom.thoughtworks.selenium.DefaultSelenium;
importcom.thoughtworks.selenium.Selenium;
/**
*多浏览器测试
*@authorhgz
*
*/
publicclassNewTestextendsTestCase{
@Test
publicvoidtestNew()throwsException{
Seleniumselenium=newDefaultSelenium("localhost",4444,"*chrome",
"");
script(selenium);
}
@Test
publicvoidtestNew2()throwsException{
Seleniumselenium=newDefaultSelenium("localhost",4444,"*iehta",
"");
script(selenium);
}
privatevoidscript(Seleniumselenium)throwsException{
try{
selenium.start();
selenium.open("selenium.open方法,浏览器会打开相应的页面
selenium.type("q","selenium");//使用type方法来给输入框输入文字
selenium.click("btnG");
selenium.waitForPageToLoad("30000");//等待页面载入
assertEquals("selenium-Google搜索",selenium.getTitle());//看看新的页面标题是不是我们想要的。
}catch(Exceptione){
throwe;
}finally{
selenium.stop();
}
}
}
六、如何选取元素
selenium提供如下强大的定位元素的方法。
id=id
name=name
dom=javascriptExpression
xpath=xpathExpression
link=textPattern
css=cssSelectorSyntax
1通过ID,name选择元素 :
如selenium.type("id=q","XX");selenium.type("name=search","XX")
2link=根据链接文字来操作:
如selenium.click("link=个人资料");
3根据XPath来选择元素 :
XPathChecker
*xpath=//img[@alt='Theimagealttext']
*xpath=//table[@id='table1']//tr[4]/td[2]
*xpath=//a[contains(@href,'#id1')]
*xpath=//a[contains(@href,'#id1')]/@class
*xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
*xpath=//input[@name='name2'and@value='yes']
*xpath=//*[text()="right"]
如:
selenium.type("xpath=//input[@name='user.email']","xxx@");//向input中type为text的栏位键入信息
selenium.check("xpath=//input[(@name='user.sex')and(@value='男')]");//向input中type为radiod