tdd and phonegap
TRANSCRIPT
WhatisTDD• It'sadevelopmenttechniquebasedonashortdevelopment
process• It'sawaytodeeplyanalyzetheexpectedbehaviorofasoftware• It'sameantoimprovethequalityofthesourcecode• It'sapracticetoenhancethedocumentationofasoftware• It'sawaytoensureasaferwaytochangethesoftwaredesign
TDDandUnitTests
TDDandUnitTests
Unittestscanbewrittenbeforewritingthecode,afterthecodehasbeenwrittenorduringthedevelopment
• UnitTestingreferstowhatyouaretesting,TDDtowhenyouaretesting• UnitTestingmeans,well,testingindividualunitsofbehavior
TheDintheMiddle• Youletthetestsdriveyou• Theteststellyouwhattodo,whattodonext,what'sdone• ThetestsaretheskeletonoftheAPIdesign
TDDWorkflow
TDDWorkflowTDDiswritingatestwhichwillfail,thenwritingtheminimum
amountofcoderequiredtomakeitrun,thenrefactoringthecodetomakeitclean
TheDattheEnd• It'ssupposedtomeandevelopmentbutoriginallywassupposed
tomeandesign• TestDrivenDesignisthedisciplineofusingUnitTestingtodesignthesoftware• Workingonabetterdesignit'spossibletoimprovethequalityofthesoftware
SmallandTestable• Methodsandfunctionsshouldbesimpleinordertobetestable• Evenbetter,thecodeneededtosatisfyatestisusuallyaverysmallchunkofcode• AsaresultthepublicAPIaresimpleandeasytomaintain
Refactoring
Usethiscataloghttp://goo.gl/Fo9VzVasareferencetoexistingrefactoringtechniques
• Restructuringexistingcodealtering(orimproving)itsinternalstructure• Don'tchangeitsexternalbehavior(ordesign)• Itshouldhappenonlywhenthealltestsarepassing
WhyRefactoring?• Toimprovetheperformances• Tocleanupthecode• Toimprovethecodereusabilityandmaintainability• Toimprovethecodereadability• Toremoveduplicatedcode
TDD+Refactoring• TDDisnotmainlyatestingstrategy,butadesignstrategy• Writingtestsfirstit'spossibletogetabetterdecoupleddesign• Abetterdecoupleddesigniseasiertorefactortoo
TDDandBugs• Nevertrustblindlydeveloper'stests• TDDisnotareplacementofQualityAssurance• Testscannotcatchallthebugs,functionaltestingisrequiredtoo
TDDTakesTooMuchTime
• Letdeveloperstosavetimepreventingandidentifyingregressionissues• Writingfailingtestsfirst,developerswillpinpointtherootoftheproblemmoreeffectively• Smallproblemswillbeidentifiedfaster
TooComplexto
TooComplextoLearn
• Notsomuch,embracingchangeandtheunknowncanbescaringforanyone• Writingtestsoncethecodehasbeenwrittenisevenmorecomplex• Writingsmalltestsbeforeyouavoidtotestahugeapplaterandallatonce
TheAppisnotDesigned
• RequiringtowriteunittestsbeforetheproductioncodeTDDdrivestoabettertaskfocus• Beingfocusedonaspecifictaskletdeveloperstobetterunderstandit• Adeeperfocusandabetterunderstandingdrivetoabetterdesign
MoreCoding• TDDmeansit'snotallowedtoskipthetestssodevelopershavetowritemorecode• Theamountofcodetomaintainisb
Increased
IncreasedComplexityUsingMocks,DIandIoC
• Mostofthetimedevelopershavetocreatemockdatatoruntests• Whenusingmocksdevelopersstarttoapplythedependencyinjection(i.e.DI)pattern• InordertousecomplexmocksdatatheInversionofControltechniqueisueused
techniqueisueused
ChangingIssues• Whenthesoftwarestarttogrowupachangeimpactsalsoa
greatnumberoftests• Developersneedmoretimetoaddresschanges
WriteValuableTests
• Atestisvaluablewhendescribeaconditiontosatisfybaseduponsoftwarerequirements• Don'twritetestsjusttocoverallthesourcecode,writethetestsfollowingastrategy
Assertions• Assertionsarestatementsthatperformanactualcheckonthesoftware’soutput• Asinglefunctioncalledassertisenoughtoexpressanycheck• TDDlibrarieshavemanyassertfunctionsforspecificneeds(assertFalse,assertEqual,s,etc.)• Asingleassertshouldbeusedineachtest• Anassertfailureshouldaddaclearmessagetothetestlogs
TestDouble
TestDoubleObjectsthetestcodecreatesandpassestotheSUTtoreplacereal
dependencies:
• dummy,objectneverusedbutneededtofillsomerequiredparameter• fake,objectthatimplementstherequiredfunctionalityinawayusefulonlyintesting• stub,objectthatcanreturnpredefinedvaluestothetestedsoftware• mock,objectthatexpectstobeusedaspecificnumberoftimesreturningpredefinedvalues
IntegrationTesting• Amid-leveltestingactivitythatverifiesacertainsetofmodulesworkcorrectlytogether• Integrationtestsarelikeunittestswithoutusingtestdoublesforsomedependencies
Fixture• Aparticularenvironmentthatmustbesetupbeforeatestcanberun
• Itgenerallyconsistsofsettingupalltestdoublesanddependenciesforthetestedsoftware
PicktheFirstTest• Carefullyreadtherequirementsandeventuallysplitthemifneeded• Choosearequirementandwritealistoftestsforthisrequirement• Selectatestthatisatomicandwellisolated
FirstTimeFailure• Howtotestsomethingthatdoesn'texist?• Byaddingmethodsorfunctionstotestdevelopersstarttodesignfirstthecode
WhyisImportant?• JavaScriptissoflexiblethatsomeruleshelptoimprovethequalityofthecode• Forcesdeveloperstorefactorthecodeandtokeepthefunctionssmallandsimple• Helpstopreventcommonregressionsissues• Isawaytobringthelanguageitselftoamoreenterpriselevel
UntestableJavaScript
varMyModule=(function(){_privateFunc=function(){};
return{publicFunc:_privateFunc
};});
addEventListener('click',myEventListener);
• Don'tincludeallthecodeinaclosurewithoutexposingapublicAPI
• Don'tuseanonymouseventhandlers,useinsteadnamedfunctions
ModelView
Qunit• Supportfortestingasynchronouscode• Nonstandard(andnonintuitive)syntax• Eightassertionsavailable• WellintegratedwithjQuery(actuallymaintainedbythejQueryteam)• DocumentedAPIhttp://api.qunitjs.com/
Phantom.js• CommandLinebased• CanusereportrunnersthatgettiedintoCIenvironments• Supportforscreencapture• Supportfortestingasynchronouscode
• Verydetailedwikihttps://github.com/ariya/phantomjs/wiki
Buster.js• RuntestsfrombrowserorheadlesswithPhantomJS• SupportsNodeJStesting• Don'tneedtorunserver/clientsondevelopmentcomputer(noneedforIE)• SupportsmultipleJavaScripttestframeworks
Karma.js• RuntestsfrombrowserorheadlesswithPhantomJS• Optiontolaunch,capture,andautomaticallyshutdownbrowsers• WritetestsxUnitorBDDstyle• SupportsmultipleJavaScripttestframeworks• Extendittowrapothertest-frameworks(Jasmine,Mocha,QUnitbuilt-in)
BrowserstackandTDD
• IntegratedwithJenkins,BambooandotherCItools• SupportfortestingtollslikeYeti,TestSwarm,BunyIP,TestEm
BehaviorDrivenDevelopment
• Helpthedevelopersdevisingthesystemidentifyappropriateteststowrite
• Helptowriteteststhatreflectthebehaviordesiredbythestakeholders
• Usesa"UbiquitousLanguage"thatcanbeunderstoodbyboththedeveloperandthecustomer.
Differences• BDDbeginswithaBandTDDbeginswithaT(MikeBrown)• BDDprovidesanewvocabularyandthusfocusforwritingaunittest• BasicallyitisafeaturedrivenapproachtoTDD
WAT?!?Itisabehavior-driventestingframeworkforJavaScriptprogramminglanguage.It’sabunchoftoolsthatyoucanusetotestJavaScript
code
• Testsshouldbesentences• Testsshouldbeverysmall
SampleTestdescribe("Helloworld",function(){it("sayshello",function(){expect(helloWorld()).toEqual("Helloworld!");});});
Suite• describe("Helloworld"...iswhatiscalledasuite• Thenameofthesuite(“Helloworld”inthiscase)definesacomponentofyourapplication
Spec• Insideofthatsuite(technically,insideofananonymous
function),istheit()block• Thisiscalledaspecification,oraspecforshort
Matcher• Inthiscase,you’retestingifhelloWorld()doesindeedreturn
"Helloworld!"• Thischeckiscalledamatcher
CustomMatchersbeforeEach(function(){this.addMatchers({theNameOfTheMatcher:function(){//Thecodetobeexecutedbythematcher}
});});
AsyncCallsit("doesanasynchronouscall",function(){
exampleAsyncCall(function(response){expect(response).toContain("somethingexpected");
done();});
});
• AJavaScripttaskrunner• Aprojectscaffoldingtool• Useittoautomatecommontaskexecutionexecution• Configurablepluginssuchasrequire.js,handlebar,jasmine,etc.
UsingGrunt• Firstofallinstallgruntcommandlinetoolnpminstall-ggrunt-cli
• Mostgrunt-inittemplateswillautomaticallycreateapackage.jsonfile
• Installgruntanthepluginsnpminstallgrunt--save-dev• Installthejasminepluginnpminstallgrunt-contrib-jasmine--save-dev