Tải bản đầy đủ - 0 (trang)
Chapter 20. Testing Your User Interfaces

Chapter 20. Testing Your User Interfaces

Tải bản đầy đủ - 0trang

Chapter20.TestingYourUserInterfaces

Introduction

TestingYourWebApplicationwithSelenium

TestingSwingGUIswithFEST

Conclusion



20.1.Introduction

Automaticallytestinguserinterfaceshasalwaysbeendifficult.

Indeed,formanyprojects,ithasoftenbeenplacedinthe"toohard"basket.Inthischapter,wewilllookattwotoolsthatcan

helpwithyourautomaticGraphicalUserInterface(GUI)

testing:SeleniumandFixturesforEasySoftwareTesting

(FEST).Seleniumisaninnovativetoolthatusesawebbrowser

toruntestsagainstyourwebapplication.AndFESTisan

equallyinnovativeproductthatletsyouintegrateSwingtesting

aspartofyourJUnitorTestNGtests.



20.2.TestingYourWebApplicationwith

Selenium

20.2.1.Introduction

Withabitofpracticeandgoodtools,itisn'tdifficulttowrite

goodunittestsforalargepartofmostapplications.Lightweight

POJO-basedframeworkssuchasHibernateandSpringmakeit

easiertodesignclassesandcomponentsthatcanbeunit-tested

inisolation.EmbeddedJavadatabasessuchasDerbyand

HSQLDB,alongwithdatabasetestingframeworkssuchas

DBUnit,makeitarelativelysimpletasktotestdatabaseaccess

layers.EJB-basedapplicationsareanexceptiontothisrule—

yougenerallyneedtodeployyourEJBsontoanapplication

serverbeforeyoucantestthemcorrectly,whichmakesunit

testingunwieldyanddifficult.

However,testingtheuserinterfaceofawebapplicationhas

alwaysbeenproblematic.Somelibraries,suchas

StrutsTestCase(seeChapter13)andtheSpringMVCtesting

framework,makegooduseofmockobjectsapproachto

simulateinteractionwiththeserver.Thesetoolsfitsmoothly

intoordinaryunittests,andareexcellentattesting(inMVC

terminology)theControllercode.However,althoughtheydoa

finejobofthis,theirlimitslieinthefactthattheyonlytestthe

applicationcode,andnottheHTMLscreensthemselves.

Othertoolsusedifferentapproaches.Some,likeHttpUnit,allow

youtowriteteststorunagainstarunningwebserver,andthen

inspectthereturnedHTMLcode.Cactusletsyoutest

applicationsbyrunningthetestsontheserveritself.JMeterlets

youdofunctionalwebtestingtosomeextent,againbybuilding

HTTPrequests.FrankCohen'sTestMakerisanotherinteresting

opensourceproductinthisfieldthatletsyourecordwebtests

inJython,editthem,andreplaythemasunittests.

Seleniumisalittledifferent.Seleniumisanopensourcetesting

tool,originallydevelopedbyThoughtWorksandnowhostedand



maintainedbyOpenQA,whichtestswebapplicationsbyusing

themasauserwould—viaabrowser.So,ratherthanbuilding

HTTPrequeststhatabrowsermightsendtotheserverand

analyzingtheresults,Seleniumdrivesarealbrowser,makingit

possibletotestmoresophisticateduserinterfaces.Selenium

worksonmostplatforms(Windows,Linux,andMacOSX)and

withmostbrowsers(Firefox,InternetExplorer,Opera,

Konqueror,Safari...),whichmakesSeleniumagoodchoice

whenitcomestoverifyingcross-browsercompatibility.



20.2.2.UsingtheSeleniumIDE

ProbablytheeasiestwaytowriteSeleniumtestscriptsistouse

theSeleniumIDE.TheSeleniumIDEisaFirefoxplug-in,which

youcandownloadandinstallfromtheSeleniumwebsite.[67]

Thistoolallowsyoutocreatetestscriptsbyusingyourweb

applicationjustasanormaluserwould,throughabrowser.

[67]http://www.openqa.org/selenium-ide/download.action



StartuptheIDEbyselecting"Tools SeleniumIDE"inyour

Firefoxmenubar.TheSeleniumIDEconsolewillcomeup(see

Figure20-1).AssoonasyouopenthisWindow,Seleniumwill

automaticallybeginrecordingyoureverymove.Nowgotothe

siteyouwanttotest.Ifyouhaven'tgotatestserver,try

SeleniumoutonyourfavoriteInternetsite—Seleniumwillwork

againstanysiteyoucanaccessfromyourbrowser.

Figure20-1.TheSeleniumIDE



Tobuildatestscript,justrunthroughyourapplicationasifyou

wereanormaluser.Typically,thiswillinvolvenavigating

throughyourapplication,enteringvaluesintoformsand

submittingthemtotheserver,andsoon.Ontheway,youcan

insertdifferenttypesofcontrolstomakesuretheweb

applicationisreturningwhatyouexpect.Atanypoint,youcan

usethecontextualmenutoinserttheequivalentofassertions—

forexample,selectablockoftextthatshouldalwaysfigureon

thispage,andthenselect"VerifyTextPresent"inthecontextual

menu(seeFigure20-2).

Figure20-2.AddingaSeleniumassertion



Youcanalsocheckforotherthingsoneachpage,suchasthe

presenceofaparticulartitle(tocheckthatyouareontheright

page,forexample).Thefullrangeofoptionsisavailableusing

the"ShowAllAvailableCommands"menuoption.

Seleniumisquitesmartabouthowitidentifiesfields,anditwill

useuniquefieldnamesoridvalueswherepossible.However,

sometimesitwilluseless-than-optimalXPathexpressions,

whichcanberetouchedbyhandtomakeyourscriptmore

robust.WewilllookathowtodothisinSection20.2.3,"laterin

thissection.

Seleniumdoesmorethansimplyrecordyouractions:itisalsoa

scriptingtoolinitsownright—asurprisinglypowerfulone.Once

youhaverecordedyourscript,youcanrerunthescript

completelyorstepthroughthecommandsone-by-one.Youcan

alsosavetheSeleniumtestscriptforfutureuse.Youcaninsert

breakpoints,deletecommands,andinsertnewones.Auseful

techniquewhenyouaretailoringyourtestscriptsistoinserta

breakpointatthecommandyouwanttomodify,andthentolet

Selenium"walk"thoughthescript(usingthe"Walk"checkbox)

untilitgetstothebreakpoint.Thenyoucanstepthroughyour

modifiedcommandsone-by-onetomakesuretheyworkas

expected.



TheCommanddrop-downlistalsogivesyouinstantaccessto

allavailableSeleniumcommands.Andjusttomakethingseven

easier,wheneveryouselectacommand,thecorresponding

documentationwillbedisplayedatthebottomoftheSelenium

window.

ItisimportanttoknowthattheSeleniumrecordingprocessis

notflawless.Sometimes,youmayneedtoretouchyourscript

togetittoworksystematically.Acommonexampleistheclick

command.Theclickcommand,asyouwouldexpect,tells

SeleniumtoclickonanHTMLelementsomewhereonyourweb

page.Quiteoften,thiswillresultinanewpagebeingloaded.

However,ifyouexpectanewpagetobeloaded,youneedto

tellSeleniumtowaituntilitisloadedbeforeproceedingtothe

nextinstruction.Theeasiestwaytodothisistouse

clickAndWaitinsteadofclick.SometimesSeleniumassumes

thatanewpagewillbeloadedandcorrectlyrecords

clickAndWaitwhenitshould.Butsometimesitdoesn't.Inthose

cases,youwillneedtogothroughyourscriptandmanually

replacetheclickcommandswithclickAndWait.

Occasionally,theclickAndWaitcommanddoesnotwaitlong

enoughforthecompletepagetoload.Inthiscase,youmay

needtosplitthecommandintoaclick,followedbyaseparate

waitForPageToLoad.

Inaddition,Seleniumwill,bydesign,recordonlythestrict

minimumofeventsthatitthinksarenecessarytoreproduce

theuseractions.Thiscancauseproblemswithmorecomplex

screens,especiallyonesthatuseAjax-backedtechnologies.We

willdiscussthefinerdetailsoftheSeleniumscriptinglanguage

inthenextsection.



20.2.3.WritingSeleniumTestScripts

TheSeleniumIDEisagreatwaytogetstartedwithSelenium

testing—itistriviallyeasytorecordandreplaytestscripts,and

tostudyhowSeleniumrecordsyourinteractionwithawebsite.

However,Seleniumalsoprovidesapowerfulscriptinglanguage



initsownright,knownas"Selenese."Togetthemostoutof

Selenium,youwillneedtounderstandhowthisscripting

languageworks.Inthissection,wewilllookathowto

understand,andwriteyourown,fullyfledgedSeleniumtest

scriptsusingthislanguage.



20.2.3.1.AnintroductiontoSelenese

ASeleniumtestscripttakestheformofanHTMLtable,made

upofthreecolumns.Thismakesitfairlyeasytoedit,eitherby

handorbyusingavisualHTMLeditor.Howevertheeasiesttool

touseisprobablytheSeleniumIDEitself.Usingthistool,you

cannotonlyinteractivelyrunyourtestscriptsbutalsodelete

commandsandinsertnewones,aswellashavedirectaccessto

thedocumentationforeachcommand.

Forconvenience,throughoutthischapterwewillberunningour

testsagainstClintonBegin'sJPetStoreapplication,whichyou

canobtainfromtheiBATISwebsite.[*]Thisisanexcellent

lightweightversionofSun'sPetStoredemoapplication,built

usingStrutsandiBATIS.Tostartoff,wewillsimplygotothe

applicationURL,andclickonthe"EntertheStore"link(see

Figure20-3).Thiswilltakeustotheapplicationhomepage

(seeFigure20-4),wherewewillverifythepresenceofthetext

"Saltwater"onthepage.

[*]http://ibatis.apache.org/javadownloads.cgi



Figure20-3.TheJPetstorewelcomepage



Eachrowofthetablecontainsacommandinthefirstcell.A

commandtakesoneortwoarguments,whichappearinthe



followingcells.AsimpleSeleniumtestscripttodothismight

looklikethefollowing:

CodeView:








PetstoreTests











JPetStoretests









open

http://testserver:8080/jpetstore/







clickAndWait

link=EntertheStore







verifyTextPresent

Saltwater





































Inamorereadableform,thistablewouldlookliketheone

shownhere:

open



http://testserver:8080/jpetstore/



clickAndWait



link=EntertheStore



verifyTextPresent



Saltwater



TheopencommandtellsSeleniumtoopenaparticularURLin

thebrowser.YoucaneitheruseafullURLasshownhere,or

simplyarelativepathsuchas"/jpetstore/".ThefullURLis

usefulwhenyouneedtodevelopand/orrunyourtestscript

usingtheSeleniumIDEfromanymachine.Therelativepathis

moreportable,butcanonlybeusedonthesamemachineas

thewebserver,usingtheapproachdescribedlateron.

ThesecondactionshownhereistheveryusefulclickAndWait

command.Thebasiccommandhereisactuallyclick;the

AndWaitsuffixtellsSeleniumtowaituntilthenewpagehas

beenloadedbeforeproceeding.Thissuffixalsoworkswithany

oftheotherSeleniumcommands(selectAndWait,typeAndWait,

andsoon),withtheexceptionofopen,wheretheAndWait

suffixisimplicit.Youshouldusethissuffixwhereverthe

commandisexpectedtoresultinanewpagebeingloaded.

ThefinalactionillustratedhereisverifyTextPresent,which,as

itsnameindicates,simplychecksforthepresenceofa

particularblockoftextontheHTMLpage.Despiteitsrather

basicnature,thissortoftestturnsouttobeusefulfor

functionaltesting.Wewilllookatother,moresophisticated

waysofcheckingresultsfurtheron.

Figure20-4.RunningtheJPetstoretestscript



Seleniumtestscriptsaredesignedtoberuneitherthroughthe

SeleniumIDE,ordirectlyonthetargetwebserver.InFigure

20-4,youcanseethisscriptbeingexecutedonaremoteserver

usingtheSeleniumIDE.



20.2.3.2.Referringtoobjectsonthewebpage

MuchofthepowerofSeleniumcomesfromitsabilitytointeract

withawebsiteusingaconventionalbrowser.Youcantell

Seleniumtointeractwithawebpageinanumberofways,such

asbyclickingonabuttonoralink,tickingacheckbox,

selectinganentryinadrop-downlist,orenteringavalueina

field.Inallofthesecases,itisvitaltobeabletoidentify

exactlywhichHTMLelementSeleniumwillbemanipulating.

Seleniumprovidesanumberofwaysforyoutoidentifyobjects

onascreenusingvarioussortsofelementlocators.Eachsortof

elementlocatorusesadifferentstrategyforfindingtarget

elements.

Byfar,theeasiestwaytoidentifyanelementistosimplyrefer



toitbynameorid.Forexample,intheJPetStoreapplication,

the"UpdateCart"buttonisimplementedasa"submit"button

withthenameattributesetto"update,"asshownhere:





Inthiscase,youcansimplyrefertothenameoftheHTML

elementdirectlyinthesecondcolumn:

clickAndWait



update



ThisisinfactashorthandnotationthatwillworkforanyHTML

elementidentifiedusingeithertheidorthenameattribute.

Moreprecisely,thisstrategywillfindanyelementwiththe

specifiedidattribute,or,failingthat,thefirstelementwiththe

specifiednameattribute.Theequivalentfullnotationwoulduse

theidentifierlocator,asshownhere:

clickAndWait



identifier=update



Thisapproachisconvenient,buttherearecasesinwhichyou

mayneedtobemoreprecise.Ifnecessary,youcanusetheid

ornamelocatorvaluesexplicitly:

clickAndWait



name=update



Anothercommonlyusedelementlocatoristhelinklocator,

whichidentifiesanHTMLlink.Forexample,supposethatwe

wanttoclickonthefollowinglink:

ReturntoMainMenu



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 20. Testing Your User Interfaces

Tải bản đầy đủ ngay(0 tr)

×