Unit testing with Spock Framework

6,044 views

Published on

Unit testing with Spock and Groovy

Published in: Technology, Education

Unit testing with Spock Framework

  1. 1. Unit TestingUnit Testingwith Spock framework
  2. 2. AgendaAgendaThree qualities of good unit testIntroduction to SpockSpock IdiomsMocks and StubsContinuous Integration PipelineCode coverage analysis
  3. 3. Why Unit testsWhy Unit tests• Catch mistakes and avoid reworksAnother production issue
  4. 4. Why Unit testsWhy Unit tests• Shape design of our code
  5. 5. Why Unit testsWhy Unit tests•Increased Productivity (shipped product)•Cheaper to solve problems
  6. 6. Trustworthiness - trustworthy tests don’t have bugsand they test the right things. They don’t “cry wolf”3 Pillars of Good3 Pillars of GoodUnit TestUnit Test
  7. 7. Trustworthiness - trustworthy tests don’t have bugsand they test the right things. They don’t “cry wolf”Maintablility - Developers will simply stop maintainingand fixing tests that takes too long to change3 Pillars of Good3 Pillars of GoodUnit TestUnit Test
  8. 8. Trustworthiness - trustworthy tests don’t have bugsand they test the right things. They don’t “cry wolf”Maintablility - Developers will simply stop maintainingand fixing tests that takes too long to changeReadability - this means not just be able to read testsbut also figuring out the problem if tests seems to bewrong. Without readability, other 2 pillars fall prettyquickly.3 Pillars of Good3 Pillars of GoodUnit TestUnit Test
  9. 9. Spock FrameworkSpock FrameworkLeverage Groovy
  10. 10. Spock FrameworkSpock FrameworkLeverage GroovyExpressive testing languageEasy to LearnReduce the line of test codeProductivityStructural blocks - BDD style -context, stimulus,expectation
  11. 11. First SpecFirst Specimport spock.lang.Specificationclass GivenWhenThenSpec extends Specification {def "test adding a new item to a set"() {given:def bag = [4, 6, 3, 2] as Setwhen:bag << 1then:bag.size() == 5
  12. 12. Feature methodFeature method// feature methoddef “test adding a new item to a set” () {// block goes here}heart of specFour phasessetup the features fixtureprovide stimulus to the systemdescribe the responseclean up
  13. 13. BlocksBlocksgiven: precondition, data fixturewhen: actions that trigger some outcomethen: makes assertions about outcodeexpect: short alt to when & thenwhere: applies varied inputssetup: alias for givenand: sub-divided other blockscleanup: post-condition, cleanup
  14. 14. CP Platform DemoCP Platform DemoUserTacticRepository.java - method findByUid(Stringuid)
  15. 15. Mock and InteractionMock and InteractionverificationverificationSpock has build-in support for mockingSubscriber sub=Mock() ordef sub=Mock(Subscriber)DSL for specifying interaction2 * sub.receive(“msg”)
  16. 16. CP DEMO InteractionCP DEMO InteractionEventController - captureEvent (Tactic dismissal forIPP event)Test class EventControllerTest1 * userTacticRepository.deactivateTactic(_,_,_)
  17. 17. StabbingStabbingImplementations can be stabbed out easily• EmailSender sender=Mock()• String send(String msg) {.... }• sender.send(_) >> “ok”
  18. 18. CP Demo StabbingCP Demo StabbingEventServiceImpl - getTargetListByUid and EventServiceTeststabbing - targetListRepository.findByUid(_) >> users
  19. 19. Testing exceptionsTesting exceptionstesting code that throws exceptions• when:• someBadMethod()• then:• def exception=thrown(IllegalStateException)• exception.message==”bad exception”
  20. 20. CP Demo - ExceptionsCP Demo - ExceptionsEvent Controller Test - sending incomplete eventobject and expect IncorrectEventException bethrown• then: ‘Exception is thrown’•thrown (IncorrectEventException)
  21. 21. Spring IntegrationSpring Integration• @ContextConfiguration([classpath:app-config.xml])• @Autowired• demo
  22. 22. HTTP callsHTTP calls• For Spring apps – use Spring REST Template• For others – use Groovy HTTP Builder or Seleniumdef http = new HTTPBuilder( http://ajax.googleapis.com )// perform a GET request, expecting JSON response datahttp.request( GET, JSON ){uri.path = /ajax/services/search/weburi.query = [ v:1.0, q: Calvin and Hobbes ]headers.User-Agent = Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4// response handler for a success response code:response.success = {resp, json -> println resp.statusLine// parse the JSON response object:json.responseData.results.each {println " ${it.titleNoFormatting} : ${it.visibleUrl}“}}
  23. 23. Spock datatablesSpock datatables
  24. 24. Spock data pipesSpock data pipes
  25. 25. There is moreThere is more@Fast - @Slow@AutoCleanUp - clean up/close resourcesAsync testing supportData Driven for parametirized testsGet it from Maven Central 07-groovy-2.0https://code.google.com/p/spock/
  26. 26. Comprehensive ApproachComprehensive Approachto Improve Qualityto Improve QualityAutomated Unit TestsAutomated Acceptance TestContinuous IntegrationCode quality analysisMeasurable values: number of defects and rework
  27. 27. Continuous IntegrationContinuous IntegrationPipelinePipeline
  28. 28. Action PlanAction Plan• Install Spock and Groovy• Write test to cover existing BUG• Write test as you write more code

×