Tải bản đầy đủ - 0 (trang)
Chapter 17. Unit and Functional Testing Applications in WSAD

Chapter 17. Unit and Functional Testing Applications in WSAD

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

17.1OverallTestingApproaches

Testingdoesnothappeninavacuum.Aswithallsoftwareengineering

endeavors,youmustfirststartwithaplan.Testing,therefore,beginswith

atestplanandthefirststepindevelopingoneistoidentifythetypesof

testingthatwillbecarriedout.Therearesomestandarddefinitionsfor

testphasesthatmostdevelopmentorganizationsadopt.Theyare:

UnittestingAunitisusuallydefinedasthesmallestpieceof

softwarethatcanbecompiledandputundertestinaparticular

language.InJava,itisusuallyequivalenttoapublicclass.

Therefore,unittestsarenormallythosethattestindividualclasses.

However,thisisn'talwaysthebestdefinition,sinceJava(andJ2EE

inparticular)provideseveralmechanismstoaggregateclassesinto

largerfunctionalunitslikeEJBs.So,forourpurposeswe'llconsider

unittestingtoencompasscomponenttestingaswell.

Functionaltesting(whichincludesintegrationtesting)The

testingofaggregatedfunctionsorwholeusecases.Functionaltests

aimtoshowthatthecombinationofcomponentsfunctionas

expected.Functionaltestslookforthingslikeconsistentdata

representations,consistentdatavalidation,andpropersequencing

ofcalls.

SystemtestingThetestingofcompletescenariosthatspanmultiple

componentsoftheapplicationtocompleteafullstory.Systemtests

canberunononlyacompletesystem;thisincludestestsforthe

nonfunctionalrequirementsofasystem,orthe"-ities"(security,

reliability,accountability,recovery,etc.)

PerformancetestingAspecialcaseofsystemtestingaimedat

determiningifperformancerequirementsaremet.Thisdeserves

specialconsiderationfortworeasons:(1)Itrequiresspecialtesting

techniques(suchasrepeated,concurrenttestrunstodeterminethe



behaviorofasystemunderload)andtestingtoolstomeasurethe

performanceofthesystem.(2)Performanceisoneofthe"-ities"that

hasthemostobviouseffectonasystem(peoplemayignorepartsof

asystemthatarecomplexordifficulttouse,buteveryonenotices

whenasystemisslow)butusuallyreceivestheleastamountof

attentionuntiltoolateinthedevelopmentcycletodoanythingabout

it.

Inthisbook,wewillonlyconcernourselveswithunitandfunctional

testing,andwaysofmakingthemeasier.Inthischapter,we'lllookat

simplestrategiesforautomatedtestingsuitableforapplicationsthatwill

runonWebSphere.WewilldiscusstheJUnittestingframeworkaswell

asprovideasimpleexampleofhowtouseJUnittowriteautomatedunit

testcases.Laterinthecasestudy,wewillrevisitJUnitandshowsome

advancedtechniquesforusingJUnitwithJ2EEapplications.

First,weneedtoexaminemorelarge-scaleissues.It'snotenoughto

simplyknowwhatyouwanttodo;atestplanisnotenoughforsuccess.

Atestplanmustbesupportedbytheselectionofappropriatetesttools,

codingstandards,andoveralltestingstrategies.



17.1.1ToolSelection

Toolandframeworkselectionfortestingisimportantandtherearemany

commercialpackagesandopensourcetoolstoselectfrom.Toolsand

frameworksshouldbeselectedfor:

UnittestThetoolselectedforunittestshouldbecapableoftesting

publicinterfaceswithoutpollutingdomainorapplicationclasses.The

codewrittentosupporttheunittestshouldgenerallynotbedeployed

withtheapplicationtoavoidpollutingtheapplicationwithtestcode

andunnecessarilyincreasingthecodebulkofyoursystem.Also,

testcodedeployedintoproductioncancreatesecurityholes,orhave

anadverseeffectonperformanceifleftinplace.So,yourunittest

toolshouldallowyoutokeeptestcodeseparatefromapplication



code,andalsotoavoiddeployingtestcodeintoproduction.

FunctionaltestToolsselectedforfunctionaltestshouldbeableto

testcomponentpublicinterfacesaswellascomponentuser

interfaces.Thecodewrittentosupportfunctionaltestingshouldnot

bedeployedwiththeapplicationforthesamereasonsasdescribed

intheunittestsection.

SystemstestThetoolselectedforsystemtestshouldbeableto

simulateuserfunctionsthatfulfillusecasestasks.Thiscouldbethe

sametoolselectedforfunctiontest,butmayneedtoinclude

extensionstosupportotherstylesoftesting.

PerformancetestThetoolselectedforperformancetestshouldbe

abletosimulateapopulationofuserstogainanunderstandingof

theapplicationloadlimitations.Thereareanumberofcommercial

optionstochoosefrom.Someofthetoolshavescriptinglanguages

tobuildtestscriptsandsimulatesystemloadandreporting.



17.1.2CodingStandards

Establishingandenforcingcodingstandardscanenhanceapplication

developmentteamcommunications,reducecodingefforts,andsimplify

testing.Establishingcodingstandardsshouldinclude:

SettingnamingstandardsFollowingcommonnamingstandards

forclasses,interfaces,members,andmethodscanleadtoabetter

understandingofthecodebydevelopersandtestersalike.This

betterunderstandingwillresultinlessrepeatedcodeandmore

reusableclasses.Thiswillreducethenumberofidenticalornearly

identicalteststhatarenecessaryintheoverallsystem.Common

namingstandardswillalsomakerefactoringeasierandpublic

interfacesmorepredictable.



InstitutemessageprotocolstandardsChainingmessagesina

longcascadinglistcanproducecodethatisdifficulttounderstand,

debug,andtest.Individualmethodscanbereducedinsize,

simplified,andmadeclearerbyestablishingrulesthatlimitthe

numberofmessagesthatcanbechained.

SettingapplicationlayerguidelinesAswe'vediscussed,

establishingapplicationlayersanddetermininglayerinterfacescan

placebehaviorinappropriatelayers,strengthencomponentpublic

interfaces,andsimplifytesting.

EstablishcommonservicesDefiningcommonservicessuchas

exceptionhandling,tracing,andloggingcanincreasereuseand

simplifytesting.Itismucheasiertolookforlogmessagesinone

locationandtoreadacommonformat,thanitistosearchseveral

differentfilesandunderstandmultipleformats.



17.1.3TestingStrategies

Establishingtherightcodingstandardsandpickingtherighttoolsare

necessarybutnotsufficientconditionsformakingtestingsuccessful.Ifa

companydoesn'ttrainitspeopleororganizeitstestingappropriately,the

besttoolswillremainshelfwarethataddsnovaluetothedevelopment

process.Herearesomestrategiesforadoptingtestpracticestomake

yourtestingmoresuccessful

Identifyclasspublicinterfacestotestearly.Makesurethatthe

developmentteamhas100percentcoverageofpublicinterfaces;

classpublicinterfacesshouldbeidentifiedandplansputinplaceto

exercisethepublicinterfacesassoonastheyareidentified.

Puttherightpeopleonthejob.Developersshouldberesponsible

fortestingtheirownclasses,whiletheteamasawholeshould

reviewtheunittestplan.Attemptstocreatespecialtestteamsto



developandexecutetestsofcomponent-levelsoftwareoftenresults

inspottytestsandconflictbetweendevelopersandtestersdueto

lackofcommunicationorincompletecommunication.



17.1.4WhyUnitTest?

Unittestingisoneofthemostimportantcontributorsinpreventing

softwaredefects.Unittestingisalsoanexcellentwaytodetermineif

thereissufficientunderstandingofthedomainmodelanditsbehavior.In

fact,manydevelopersprefertodevelopthetestcasesfirst,essentiallyas

theimplementationofapplicationusecases,andthendevelopthe

domainmodelsufficientlytoexecutethetests.Thisissometimescalled

needs-basedprogrammingortest-drivendevelopment.

Unittestsdonottypicallyvalidateuserinterfacefunctionsorverify

systemlevelfeatures,althoughyoucanexpandthedefinitiontoinclude

theseconcepts.Theyareinsteadmostoftenconcernedwithvalidating

thattheapplication'sdomainandinfrastructureclassesfunctionas

expected.Usecasesareoftenagoodsourceoftestcasesastheyfocus

onthefunctionalitythathasvaluetothecustomer.However,suchtests

wouldn'tnecessarilyhavetoincludeuserinterfaceconsiderations.

Withasetofunittestsinplace,youcanbeconfidentthataddinganew

functionorchanginganythingwillnotwreakhavoconthefunctionyou

haveimplemented.Whatisnecessarytoachievethislevelofcomfortisa

toolthatallowsyoutoeasilycreatetestsfornewfunctions,andalso

easilyreruntestsonexistingfunctions.Luckily,wehavethatin

WebSphereStudiointheJUnitframework,aswewillseeinthenext

section.



17.2WhatIsJUnit?

TheJUnitTestFrameworkisanopensourceunittestframeworkforJava

availablefromjunit.org.TheideabehindJUnit(expressedin[Beck])is

thatifregressiontestingismadesimpleenough,developerswillfindthat

creatingautomatedtestcasesisnoharderthanrunningtestcases

manually.Thisframeworksupports:

Thecreationofunittestcaseswithnochangeinapplicationcode.

Unittestcasescanbecreatedwithnoimpactontheapplication.

Theabilitytoautomateregressionunittesting.

Theabilitytocreatereusabletestfixtures(sampledata).

Theabilitytocreatetestcaseswithoutmodifyingtheapplication.

YoushouldwriteJUnitteststovalidateyourpublicinterfacemethods,not

totesttrivialcodelikegettersandsetters.JUnittestcasesarebest

suitedtodecidequestionssuchaswhetherdomainobjectscanbe

createdandtraversedproperly,ifexceptionsarethrownandhandled

correctly,orifpersistentdataretrievalandupdateishandledintheright

way.

TheJUnittestcasesandexecutabletestsuitesarenotembeddedinthe

application.Theexecutabletestsuitecanbemodifiedtoregressiontest

portionsoftheapplication.TheJUnitTestFrameworkisshippedwithIBM

WSADandcontainssupportfortestassertions,testcases,testsuite

development,andtestreporting(Figure17.1).



Figure17.1.JUnitTestFrameworkandapplication.



TheJUnitframeworkAPIisfairlyeasytouse.Thethreeprimary

packagesthatyouwilluseare:

junit.frameworkcontainsclassesandinterfacestosupporttest

assertionsandtestcases

junit.extensionsprovidesadditionalsupportfortestsetupand

exceptionhandling

junit.textuisupportsanexecutablesuiteoftestcases

Thejunit.frameworkpackagecontainsmostoftheclassesand

interfacesyouwillusetounittestyourapplication:

Assertclassthatcontainsasetoftestassertionmethods

Testinterfacetoruntestcasesandcollectresults



TestCaseclassfixturetorunoneormoretests

TestResultclassthatcollectsresultsofexecutedtestcase

TestSuiteclassthatcollectstestcases

AssertionFailedErrorexceptionthrownwhentestassertionfails

TestListenerclassthatlistensfortestprogress

TheAssertclassisparticularlyhelpfulasitprovidesassertionmethods

thatyourtestcasescanusetocheckyourapplication.Themethodsof

theAssertclassareshowninFigure17.2.



Figure17.2.Assertclassassertionmethods.



AcloserlookattheAPIshowsthattheTestCaseclassusestheAssert

classtoprovidetheassertionstotestyourapplication.Inyourtestcases

youextendTestCase,whichisanabstractclass,(forexample,MyTest).

Youwillalsocreateaclassthatidentifiesandrunsthetestsuite,(for

example,AllTests).SeeFigure17.3.



Figure17.3.Classhierarchyandimplementation.



package

com.ibm.junit.domain;
class="docEmphStrong">import

java.util.Enumeration;
class="docEmphStrong">importjava.util.Vector;

publicclass

Department{

staticint

noEmployees=0;
class="docEmphStrong">privateString

departmentName=
class="docEmphStrong">null;
class="docEmphStrong">privateString

departmentType=
class="docEmphStrong">null;
class="docEmphStrong">privateVector

employees=
class="docEmphStrong">null;
class="docEmphStrong">publicDepartment(){

super();

employees=
class="docEmphStrong">newVector();}



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

Chapter 17. Unit and Functional Testing Applications in WSAD

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

×