tdd and phonegap

81

Upload: giorgio-natili

Post on 02-Aug-2015

37 views

Category:

Mobile


3 download

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

DisadvantageofTDD

MoreCoding• TDDmeansit'snotallowedtoskipthetestssodevelopershavetowritemorecode• Theamountofcodetomaintainisb

Increased

IncreasedComplexityUsingMocks,DIandIoC

• Mostofthetimedevelopershavetocreatemockdatatoruntests• Whenusingmocksdevelopersstarttoapplythedependencyinjection(i.e.DI)pattern• InordertousecomplexmocksdatatheInversionofControltechniqueisueused

techniqueisueused

ChangingIssues• Whenthesoftwarestarttogrowupachangeimpactsalsoa

greatnumberoftests• Developersneedmoretimetoaddresschanges

PragmaticTDD

WriteValuableTests

• Atestisvaluablewhendescribeaconditiontosatisfybaseduponsoftwarerequirements• Don'twritetestsjusttocoverallthesourcecode,writethetestsfollowingastrategy

ChoosetheRightTests

• Acceptancetests• Smoketests• Integrationtests• Performanceandloadtests

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

Source&TestsSeparation

PicktheFirstTest• Carefullyreadtherequirementsandeventuallysplitthemifneeded• Choosearequirementandwritealistoftestsforthisrequirement• Selectatestthatisatomicandwellisolated

WritetheAssertionFirst

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

ModelViewPresenter

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)

EvenMore• Mocha.js• JsTestDriver• YUIYeti• Casper.js• Etc.

BrowserstackandTDD

• IntegratedwithJenkins,BambooandotherCItools• SupportfortestingtollslikeYeti,TestSwarm,BunyIP,TestEm

BehaviorDrivenDevelopment

• Helpthedevelopersdevisingthesystemidentifyappropriateteststowrite

• Helptowriteteststhatreflectthebehaviordesiredbythestakeholders

• Usesa"UbiquitousLanguage"thatcanbeunderstoodbyboththedeveloperandthecustomer.

Differences• BDDbeginswithaBandTDDbeginswithaT(MikeBrown)• BDDprovidesanewvocabularyandthusfocusforwritingaunittest• BasicallyitisafeaturedrivenapproachtoTDD

JasmineReadytomeetasupercoollady?:)

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

toBeDefined&

toBeUndefined

toBeTruthy&

toBeFalsy

toBeLessThan&

toBeGreatherThan

toBe

toEqual

toMatch

toBeCloseTo

toBeNaN

toBeNull

toContain

toThrow

Expectations

CustomMatchersbeforeEach(function(){this.addMatchers({theNameOfTheMatcher:function(){//Thecodetobeexecutedbythematcher}

});});

beforeach&aftereach

Theyallowyoutoexecutesomecodebeforeandaftereachspec

AsyncCalls

AsyncCallsit("doesanasynchronouscall",function(){

exampleAsyncCall(function(response){expect(response).toContain("somethingexpected");

done();});

});

Evenmore...Refertotheonlinewikihttps://github.com/pivotal/jasmine/wiki

• AJavaScripttaskrunner• Aprojectscaffoldingtool• Useittoautomatecommontaskexecutionexecution• Configurablepluginssuchasrequire.js,handlebar,jasmine,etc.

UsingGrunt• Firstofallinstallgruntcommandlinetoolnpminstall-ggrunt-cli

• Mostgrunt-inittemplateswillautomaticallycreateapackage.jsonfile

• Installgruntanthepluginsnpminstallgrunt--save-dev• Installthejasminepluginnpminstallgrunt-contrib-jasmine--save-dev

TheGrunt.jsFile

DefaultProject

RunandCompile

Thebenefits

Questions&Answers

Hereaslidetohelpmetobreakdownthedistancebetweenmeandtheaudience