test first!

73

Upload: giorgio-natili

Post on 13-Aug-2015

32 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Test first!
Page 2: Test first!
Page 3: Test first!
Page 4: Test first!

TestDrivenDevelopment

Page 5: Test first!

WhatisTDD• It'sadevelopmenttechniquebasedonashortdevelopment

process• It'sawaytodeeplyanalyzetheexpectedbehaviorofasoftware• It'sameantoimprovethequalityofthesourcecode• It'sapracticetoenhancethedocumentationofasoftware• It'sawaytoensureasaferwaytomodifythesoftwarebehavior

Page 6: Test first!

TDDandUnitTests

Unittestscanbewrittenbeforewritingthecode,afterthecodehasbeenwrittenorduringthedevelopment

• UnitTestingreferstowhatyouaretesting,TDDtowhenyouaretesting

• UnitTestingmeans,well,testingindividualunitsofbehavior

Page 7: Test first!

TheDintheMiddle• Youlettheteststodriveyou• Theteststellyouwhattodo,whattodonext,what'sdone• ThetestsaretheskeletonoftheAPIdesign

TDDWorkflow

Page 8: Test first!

TDDWorkflowTDDiswritingatestwhichwillfail,thenwritingtheminimum

amountofcoderequiredtomakeitrun,thenrefactoringthecodetomakeitclean

Page 9: Test first!

TheDattheEnd• It'ssupposedtomeandevelopmentbutoriginallywassupposed

tomeandesign• TestDrivenDesignisthedisciplineofusingUnitTesting(or

othertests)todesignthesoftware• Workingonabetterdesignit'spossibletoimprovethequalityof

thesoftware

Page 10: Test first!

SmallandTestable• Methodsandfunctionsshouldbesimpleinordertobetestable• Generallyspeaking,thecodeneededtosatisfyatestisusuallyaverysmallchunkofcode• AsaresultthepublicAPIaresimpleandeasytomaintain

Page 11: Test first!

TestDoubleThegeneralnameforobjectsusedtoreplacerealcomponentservers

fortestingpurposes

• Dummy,anobjectwithoutanyspecificimplementation• Stub,anobjectwithinterfaceorminimalimplementation

• Spy,astepupfromstubbecauseitrecordswhichobjectuseditself

• Fake,anobjectwithamorecompleximplementation• Mock,anobjectdynamicallycreatedbyalibrary(e.g.

http://sinonjs.org)

Page 12: Test first!

CommonSentences• “Itcoststoomuchtime,we’dbetterfixthesebugsfirst”

• “Oursystemistoobigforunittests”• “Wejustoughttobemorecarefulnottointroducebugs,that

willhelpusalot”• “Oursystemisnotsuitedforunittests”

• “WehaveaQA-teamthatwilldetecterrors”

Page 13: Test first!

TDDandQA• Testdrivendevelopmentisnotaqualityassurancemethod• Mostpeopleassociate"testing"with"qualityassurance"

• WithTDDyouwritecodeusingtestsasatool,theQAteamsearchesbugsusingthesametestsasatool

Page 14: Test first!

BestPractices

Page 15: Test first!

Assertions• Assertionsarestatementsthatperformanactualcheckonthesoftware’soutput• Asinglefunctioncalledassertisenoughtoexpressanycheck• TDDlibrarieshavemanyassertfunctionsforspecificneeds(assertFalse,assertEqual,s,etc.)• Asingleassertshouldbeusedineachtest• Anassertfailureshouldaddaclearmessagetothetestlogs

Page 16: Test first!

IntegrationTesting• Amid-leveltestingactivitythatverifiesacertainsetofmodulesworkcorrectlytogether• Integrationtestsarelikeunittestswithoutusingtestdoublesforsomedependencies

Page 17: Test first!

Source&TestsSeparation

Page 18: Test first!

PicktheFirstTest• Carefullyreadtherequirementsandeventuallysplitthemifneeded• Choosearequirementandwritealistoftestsforthisrequirement• Selectatestthatisatomicandwellisolated• Trytoprioritizethem(e.g.testfirstusercreationthanlogin!)

Page 19: Test first!

WritetheAssertionFirst

Determinehowthespecification(i.e.thetest)isgoingtobevalidated

Page 20: Test first!

FirstTimeFailure• Howtotestsomethingthatdoesn'texist?• Byaddingmethodsorfunctionstotestdevelopersstarttodesignfirstthecode

Page 21: Test first!

UnitTesting(UnitTestingreferstowhatyouaretesting,TDDtowhenyouare

testing)

Glossary

Page 22: Test first!

Glossary• Unit,thesmallestpieceofcodesoftwarethatcanbetestedin

isolation• Assertion,it'sapredicatethatstatestheprogrammer’s

intendedstateofasystem• Integrationtest,atestthatgooutsidethecurrentprocess

interactingwithsomethingelse• Interactiontest,atestonthewaythatobjectsworktogether• Fake,anystand-inobjectthat'susedinsteadoftherealthing• Stub,astand-inobjectthatprovidesadependencyrequiredby

thecodeundertest• Mock,asimulatedobjectthatmimicsaspecificbehavior

Page 23: Test first!

IndividualUnits• Sourcecodeistestedtounderstandifitcanbeusedbyother

partofthesoftware• Testcasesareseparatedandindependentbyeachother

• Methodstubs,mockobjectsandfakesdatacanbeusedtorunthetestsinisolation

Page 24: Test first!

Benefits• Helpsfindingproblemsearly

• Facilitateschanges(i.e.regressionstesting)• Simplifiesintegration

• Improvesthedocumentation

Page 25: Test first!

Limitations• Unittestingwillnotcatcheveryerrorintheprogram

• Integrationerrorswillbenotcatchbecausethetestitselfbydefinitiontestonlytheunit

• Codecoveragedoesn'tprovethesoftwareisworking• It'stimeconsuming

Page 26: Test first!

CommonChallenges• Settinguprealisticandusefultests

• Testingasynchronouscode• Testingprivatemethods• Writingflexibletests

• Effectivenames

Page 27: Test first!

Usefulness• Definerelevantinitialconditions

• Testshavetoexercisingthecodeinarealisticcontext• Avoidunnecessarypreconditions

• Don’tunit-testconfigurationsettings

Page 28: Test first!

Flexibility• Testsshouldneveroverspecifythebehaviorofthetargetcode• Testsshouldnevertestmorethanoncethesamecode(i.e.

don'trepeatyourself!)• Alwaysuseonlydatarelevanttoaparticulartestinthetest• Consideralwayshowtopassinputdata(e.g.Builderpattern)

Page 29: Test first!

AsyncCode• Themainissueistokeepthetestblockeduntiltheasynccode

hasbeenexecuted• Youcanrepeatedlypollingthetargetsystemforastatechange

(i.e.Sampling)• Youcanuseanevent-basedassertionthatwaitsforaneventby

blockingonamonitoruntilitgetsnotifiedortimesout(i.e.Listening)

Page 30: Test first!

PrivateMethods

Eventshandler,alsoifprivate,areyourpublicAPI

• Putthetestsintheclassyouwanttotest• Putthetestsinanotherclass/sourcefile&exposetheprivate

methodsyouwanttotestaspublicmethods

Page 31: Test first!

Naming• Thenameshouldclearlyindicatethetestedfeature

• Thetestnameshouldindicateswhattheunitdoesnotwhattheunitis

• Thetestnameshouldsaysomethingaboutthemotivationforthescenario

• UsetheTestDoxconventionwhereeachtestnamereadslikeasentence

Page 32: Test first!

AcceptanceTestDriven

Development

Page 33: Test first!

KeyFeatures• ATDDisapracticeinwhichthewholeteamcollaboratively

discussesrequirementsacceptability• ATDD,likeTDD,involvescreatingtestsbeforecode

• Theacceptanceteststhenbecomelikeexecutablerequirements

Page 34: Test first!

ExpectedBenefits• ATDDresultsinapplicationsdesignedtobeeasiertotest

• ATDDfavorsthecreationofinterfacesspecifictofunctionaltesting

• ATDDclarifytoalltheteammemberswhicharethecustomerexpectations

Page 35: Test first!

ATDDandUnitTesting

• ATDDdoesn'timplytoremoveunittestingfromthedevelopmentcycle

• ATDDimpliestheusageoftoolstoautomatethefunctionaltestingexecution(e.g.FitNess,Cucumber,Rspec)

Page 36: Test first!

TestingPyramid

Software

Page 37: Test first!

SoftwareRequirements

Asa<role>Iwantto<goal>sothat<motivation>

• Userstoriesarethecentralaxisaroundwhichasoftwareprojectrotates

• UserstoriesexpressrequirementsintermsofTheRole,TheGoal,andTheMotivation

• Userstoriesaren’texhaustiverequirementsspecifications

Page 38: Test first!

AcceptanceCriteria• Asetofconditionstherequirementmustfitintobeconsidered

done• It'stheresultofaconversationwiththecustomer(orproduct

owner)• It'sawaytodescribethetestsarequirementshouldpass

Page 39: Test first!

WritingAcceptanceCriteria

• AnacceptancecriteriashouldcontainanActor,aVerbandanObservableResult

• Anacceptancecriteriadescribeapre-condtionwhenanactorshouldperformanactionandobtaintheexpectedresult(e.g.

mandatoryfields)• Anacceptancecriteriashouldbealsoidentifyperformances

expectations

Page 40: Test first!

AcceptanceTests

Concreteexamples,concretebehavior,noambiguity

• Aformaldescriptionofthebehaviorofasoftwareproductexpressedasanexample

• Arethecombinationofacceptancecriteriaandrealexamples(i.e.dataandscenarios)

ATDDCycle

Page 41: Test first!

ATDDCycle

Page 42: Test first!

BehaviorDrivenDevelopment

Page 43: Test first!

KeyFeatures• Helptowriteteststhatreflectthebehaviordesiredbythe

stakeholders• UsesaUbiquitousLanguagethatcanbeunderstoodbyboththe

developerandthecustomer

Page 44: Test first!

TestDifferent• Unittestingforcedeveloperstothinkintermsoftestsandassertionswhilebehaviordrivendevelopmentbringthemto

considertestsaspartofspecification• Whenyourealizethatit'sallaboutspecifyingbehaviorandnot

writingtests,yourpointofviewshifts

Page 45: Test first!

It’sStillTDD?NothinginBehavior-DrivenDevelopmentchangesTestDriven

Development’smechanics(i.e.writethetest->passit->refactor)

Page 46: Test first!

BDDandCodeDesign

• Unittestingisoftenspecificallyaboutthedesignofcodeunitsandmodulessuchasclasses

• BDDisalsoconcernedwithunitdesign,butaddressesabroaderrangeofdesignconcerns

Page 47: Test first!

BDDandAcceptanceCriteria

• Acceptancecriteriaaretransformedintolower-levelspecificationswrittenincode,andexecutedusingatestingor

specificationframework

Page 48: Test first!

SignofUse• Significantportionof"functionaldocumentation"isintheformofUserStoriesaugmentedwithexecutablescenariosorexamples• Insteadofreferringto"tests",teammemberswillpreferthe

terms"scenario"and"specification"• Testsareameantodefinethespecificationsofthebehaviorof

aModule

Page 49: Test first!

CommonIssues• BDDrequiresfamiliaritywithagreaterrangeofconceptsthan

UnitTestingdoes• BDDdon'trequiresatthebeginningparticulartoolsor

programminglanguages,andisprimarilyaconceptualapproach• BDDrequiresadifferentdevelopmentcycle

Page 50: Test first!

BDDCycle

Page 51: Test first!

ContextandSpecifications

• Setsofrelatedobservations(tests)willbegatheredintocontexts

• Contextsaren’tsimplyarbitrarygroupings,theyrepresentcohesiveandconsistentcircumstancesthatsoftwaremodulescan

befoundin• SpecificationsarethetestswrittenusingaBDDtesting

framework

Page 52: Test first!

EffectiveScenarios• Captureasummaryscenario• Identifyactorsandtheirgoals

• Sentencesshouldbeinsequentialorder• Eachsentenceshouldhaveanactorperforminganaction

Page 53: Test first!

UnitTesting,ATDDandBDD

BDDisanevolutionoftest-drivendevelopmentthatenhanceandenforcethepracticesderivingfromunittestingandacceptance

testing

TDD===BDD

Page 54: Test first!

TestsAnatomy

Page 55: Test first!

UnitTeststest("prettydatebasics",function(){varnow="2008/01/2822:25:00";equal(prettyDate(now,"2008/01/2822:24:30"),"justnow");equal(prettyDate(now,"2008/01/2822:23:30"),"1minuteago");equal(prettyDate(now,"2008/01/2821:23:30"),"1hourago");equal(prettyDate(now,"2008/01/2722:23:30"),"Yesterday");equal(prettyDate(now,"2008/01/2622:23:30"),"2daysago");equal(prettyDate(now,"2007/01/2622:23:30"),undefined);});

Page 56: Test first!

ATDDTests

Page 57: Test first!

BDDTestsfunctionaddValues(a,b){returna+b;}

describe("addValues(a,b)function",function(){it("shouldequal3",function(){expect(addValues(1,2)).toBe(3);});it("shouldequal3.75",function(){expect(addValues(1.75,2)).toBe(3.75);});it("shouldNOTequal'3'asaString",function(){

Page 58: Test first!

Jasmine(JavaScripttestingsuite)

Page 59: Test first!

JasmineProvides• AnaturalBDDsyntaxfororganizingthetestlogic

• Asynchronoustestingsupport• Mocksobject

• Spies• Custommatchers

Page 60: Test first!

SampleTestdescribe("Helloworld",function(){it("sayshello",function(){expect(helloWorld()).toEqual("Helloworld!");});});

Page 61: Test first!

Suite• describe("Helloworld"...)iswhatiscalledasuite• Thenameofthesuite(“Helloworld”inthiscase)definesacomponentofyourapplication

Page 62: Test first!

Spec• Insideofthatsuite(technically,insideofananonymous

function),istheit()block• Thisiscalledaspecification,oraspecforshort

Page 63: Test first!

Matcher• Inthiscase,you’retestingifhelloWorld()doesindeedreturn

"Helloworld!"• Thischeckiscalledamatcher...Jasminesupportsseveralmatchers!

Page 64: Test first!

Specs.htmlItcontainsfourscripttags:

• ThefirstsectionincludestheJasminetestrunnerfiles• Inthenexttwosections,youreferenceyourJavaScriptcodeto

betestedaswellasthetests• Thefourthrunsthetests

Page 65: Test first!

AsyncCallsit("doesanasynchronouscall",function(){

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

});RunningTestswith

Page 66: Test first!

RunningTestswithGrunt

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

Page 67: Test first!

• Configurablepluginssuchasrequire.js,handlebar,jasmine,etc.

UsingGrunt• Firstofallinstallgruntcommandlinetoolnpminstall-ggrunt-cli

• Mostgrunt-inittemplateswillautomaticallycreateapackage.jsonfile

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

Page 68: Test first!

TheGrunt.jsFilemodule.exports=function(grunt){'usestrict';grunt.initConfig({jasmine:{src:'src/**/*.js',options:{specs:'spec/**/*.js',template:require('grunt-template-jasmine-istanbul'),templateOptions:{coverage:'reports/coverage.json',report:'reports/coverage'}

Page 69: Test first!

Questions&Answers

Links

Page 70: Test first!

Links• http://msdn.microsoft.com/en-us/magazine/cc163358.aspx

• http://guide.agilealliance.org/guide/atdd.html• http://guide.agilealliance.org/guide/acceptance.html

• http://www.codemag.com/article/0805061• http://www.slideshare.net/nashjain/acceptance-test-driven-

development-350264• http://testobsessed.com/wp-

content/uploads/2011/04/atddexample.pdf• http://programmers.stackexchange.com/questions/135218/what-

is-the-difference-between-bdd-and-tdd• http://www.slideshare.net/emwendelin/test-your-javascriptMyLatestBook

Page 71: Test first!

• http://www.slideshare.net/emwendelin/test-your-javascriptMyLatestBook

Page 72: Test first!

What'sNext

Page 73: Test first!