Tải bản đầy đủ - 0 (trang)
Chapter 11. Next-Generation Testing with TestNG

Chapter 11. Next-Generation Testing with TestNG

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

suchasEclipseandbuildtoolslikeAntandMaven.Allofthese

featuresmakeiteasiertowritebetter-designed,fasterand

moreflexibleunittests.



Chapter11.Next-GenerationTesting

withTestNG

IntroducingTestNG

CreatingSimpleUnitTestswithTestNG

DefiningTestNGTestSuites

TheTestNGEclipsePlug-In

UsingTestNGinAnt

UsingTestNGwithMaven2

ManagingtheTestLifecycle

UsingTestGroups

ManagingDependencies

ParallelTesting

TestParametersandData-DrivenTesting

CheckingforExceptions

HandlingPartialFailures

RerunningFailedTests



11.1.IntroducingTestNG

TestNGisaninnovativeunittestframework,writtenbyCédric

BeustandAlexandruPopescu,designedtoovercomemanyof

theperceivedshortcomingsofJUnit3(seeSection10.1).Like

JUnit4,TestNGimprovesonJUnit3inmanyways,removing

syntacticalconstraintsandaddingflexible,nonintrusive

annotation-basedtesting.Inaddition,TestNGalsosupports

manypowerfulfeaturessuchastestgroups,dependencies,and

paralleltesting—featuresthatarenotyetsupportedbyJUnit4

atthetimeofthiswriting.TestNGintegrateswellwithIDEs



suchasEclipseandbuildtoolslikeAntandMaven.Allofthese

featuresmakeiteasiertowritebetter-designed,fasterand

moreflexibleunittests.



11.2.CreatingSimpleUnitTestswith

TestNG

BeforediscussingthemoreadvancedfeaturesofTestNG,we

willtakeaquickintroductorytour.Let'slookathowtoget

startedwithTestNG.

TestNGclassesareordinaryJavaclasseswithordinary

methods:Theydon'thavetoextendaparticularclass,nordo

theirmethodshavetofollowanyparticularnamingconvention.

Yousimplyusethe@Testannotationtoflagunittestmethods,

anduseJava5assertstotestcalculatedvaluesagainst

expectedones.Throughoutthischapter,wewillusethe

exampleofaclassthatcalculatesGST(goodsandservicestax,

alsoknownasavalueaddedtaxinsomecountries),whichwe

introducedinSection10.1.Thisclassissupposedtocalculate

thenetpriceofsomething,takingintoaccountthecurrentGST

rate.SupposethatthestandardGSTrateis12.5percent.Our

unittestclassmightlooklikethis:



importorg.testng.annotations.Test;



publicclassPriceCalculatorTests{



@Test

publicvoidcalculateGST(){

PriceCalculatorcalculator=newPriceCalculator();

doubleamountWithGst=calculator.calculateGST(100.00);

assert(112.50==amountWithGst):"StandardGSTshould

}

}



YoumayprefertheoldJUnit3assertmethods(assertEquals(),

andsoon).TestNGviaalsosupportsthesebyusingstatic

imports.ThisapproachisalsousedbyJUnit4(seeSection

10.2).



CodeView:



importorg.testng.annotations.Test;

importstaticorg.testng.Assert.assertEquals;



publicclassPriceCalculatorTests{



@Test

publicvoidcalculateGST(){

PriceCalculatorcalculator=newPriceCalculator();

doubleamountWithGst=calculator.calculateGST(100.00);

assertEquals("StandardGSTshouldbe12.5%",amountWith

}

}

























Testframeworksgenerallyletyoudefinecodethatneedstobe

runbeforeeverytest.InJUnit3.x,youoverridethesetUp()and

tearDown()methods.TestNGcomeswitharichsetof

annotationsfordifferenttypesoffixturecode(seeSection

11.7).Inthefollowingexample,weusethe@BeforeMethod

annotationtoensurethattheinit()methodiscalledbeforeeach

andeverytestcase.Conversely,weusethe@AfterMethod

annotationtomakesurethetidyUp()functioniscalledafter

eachtest:

CodeView:

importorg.testng.annotations.Test;

importstaticorg.testng.Assert.assertEquals;



publicclassPriceCalculatorTests{



PriceCalculatorcalculator=newPriceCalculator();



@BeforeMethod



publicvoidinit(){

calculator=newPriceCalculator();

}



@Test

publicvoidcalculateGST(){

doubleamountWithGst=calculator.calculateGST(100.00);

assertEquals("StandardGSTshouldbe12.5%",amountWith

}



@AfterMethod

publicvoidtidyUp(){

...

}

}

























ThereareseveralwaystorunTestNGtests.Youcanrunit

directlyfromthecommandline,butthisoptionisnotvery

practicalforanythingotherthantoyexamples.Youcanalsorun

TestNGtestsdirectlyfromwithinEclipseusingtheTestNGplugin(seeSection11.4).Oryoucanintegratethemintoyourbuild

environmentusingAnt(seeSection11.5)orMaven(see

Section11.6).WhenyourunasetofTestNGtests,itproduces

areportsimilartothetraditionalJUnitreports,although,like

JUnit4andunlikeJUnit3.x,nodistinctionismadebetween

failedassertionsandexceptions.Thefollowinglistingisan

exampleofrunningTestNGusingtheAnttask:

$anttest

...

test:

[testng][Parser]Running:

...

[testng]PASSED:findHotelsInCity

[testng]PASSED:calculateGST



[testng]PASSED:calculateReducedGST

[testng]PASSED:calculateStandardGST



[testng]===============================================

[testng]Anttest

[testng]Testsrun:1037,Failures:0,Skips:0

[testng]===============================================



[testng]===============================================

[testng]Antsuite

[testng]Totaltestsrun:1037,Failures:0,Skips:0

[testng]===============================================

ThisisjustaquickoverviewofTestNGtests,whichshouldlet

yougetthefeeloftheAPI.Therearemanyotherannotations

andfeatures,suchasgroupsanddependencies,whichwewill

investigatelateroninthischapter.



11.3.DefiningTestNGTestSuites

Traditionally,TestNGunittestsaregenerallyorganizedintotest

suites.InTestNG,atestsuiteisalogicalsetofteststhatyou

expecttoruntogether.YoudefineTestNGtestsuitesusinga

TestNGconfigurationfile,anXMLconfigurationfilethattells

TestNGhowyourtestsareorganizedandwhereitneedstolook

forthem.ThisisalittlemorecomplicatedthanaJUnittest

configuration,where,ifyouareusingMaven(seeSection11.6)

orAnt(seeSection11.5),youcangetawaywithjustwriting

testclassesandplacingtheminthetestsourcecodedirectory,

withouthavingtosetupaTestNGconfigurationfile.Butit's

sometimesworththeextraeffortofusingTestNGconfiguration

filesfortheflexibilityandreadabilityitgivesyou.

Hereisasimpletestsuiteconfigurationfile.Here,wesimplylist

thetestclasseswewanttotest:



























TestNGsupportsbothJava5annotationsandtheolderJavadocstyleannotationsforJDK1-4.Theannotations="JDK"attribute

inthepreviouslistingindicatesthatweareworkingwithJava5

annotations,whichiswhatwewillusethroughouttherestof

thischapter.



Youcanalsospecifyalistofpackagesratherthanalistof

classes,whichwillrunallthetestscontainedinthespecified

package:

















Tomakethingsevensimpler,youcanusewildcardcharactersin

packageandclassnames.Thefollowingtestsuiteincludesany

classesinanypackagesdirectlyorindirectlycontainedinthe

com.wakaleo.jptpackage:

















UsingconfigurationfilesinTestNGisnotobligatory.Inmany

cases,itismoreconvenienttorunTestNGagainstasetof

classes,usingtestgroupsifnecessarytodecidewhichtests

shouldorshouldnotbeexecuted(seeSection11.8),whichyou

candofairlyeasilyinAntordirectlyfromEclipse(seeSection

11.4).However,configurationfilesaresometimesusefulto

organizeyourtestsinaclearandreadablemanner.



11.4.TheTestNGEclipsePlug-In

Oneofthemosteffectivewaystorununittestsisfromwithin

anIDEsuchasEclipseorNetBeans.Thisapproachallowsa

moreseamlessdevelopmentprocessandatightertestingcycle.

Atthetimeofthiswriting,TestNGplug-insexistforEclipseand

IntelliJ.Inthissection,wewilllookathowtoinstallandusethe

EclipseTestNGplug-in.Thisexcellentpieceofsoftwareprovides

invaluabletoolsforwriting,maintaining,andrunningyour

TestNGtestcasesfromwithinEclipse.



11.4.1.InstallingtheTestNGPlug-In

YouinstalltheTestNGplug-infromtheRemoteUpdatesitein

theusualway:

1. Openthe"Install/Update"window(Help



Software

updates FindandInstall)andselect"Searchfor

newfeaturestoinstall."



2. Createa"NewRemoteSite."

3. Enterhttp://beust.com/eclipsefortheURLand



"TestNGPlugin"(orsomeotherappropriatename)

forthename.

4. Makesurethe"TestNGPlugin"checkboxischecked



inthesitelist,andclick"Finish."

5. Inthenextwindow,checkthe"TestNG"boxinthe



featurestoinstall,andstepthroughtheinstallation

process.

Onceyouhavefinished,youmayneedtorestartEclipse.You

canverifytheinstallationbyopeningtheTestNGview(Windows

ShowView Other…),asshowninFigure11-1.Thiswillopen

theTestNGdashboardatthebottomofthescreen.



Figure11-1.OpeningtheTestNGviewinEclipse



11.4.2.RunningTestNGTests

RunningaTestNGtestclass,oranindividualTestNG-annotated

unittestinEclipseisintuitiveandeasy,andverysimilarto

whatyouwoulddoforaJUnittestcase:justselecttheclassor

methodintheOutlineviewandselect"RunAs TestNGTest"in

thecontextualmenu(seeFigure11-2).Thiswillrunthe

correspondingtestsanddisplaytheresultsintheConsoleview

andintheTestNGresultsview(seeFigure11-3).Ifyouwantto



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

Chapter 11. Next-Generation Testing with TestNG

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

×