KEMBAR78
Unit testing with Spock Framework | PPT
Unit TestingUnit Testing
with Spock framework
AgendaAgenda
Three qualities of good unit test
Introduction to Spock
Spock Idioms
Mocks and Stubs
Continuous Integration Pipeline
Code coverage analysis
Why Unit testsWhy Unit tests
• Catch mistakes and avoid reworks
Another production issue
Why Unit testsWhy Unit tests
• Shape design of our code
Why Unit testsWhy Unit tests
•Increased Productivity (shipped product)
•Cheaper to solve problems
Trustworthiness - trustworthy tests don’t have bugs
and they test the right things. They don’t “cry wolf”
3 Pillars of Good3 Pillars of Good
Unit TestUnit Test
Trustworthiness - trustworthy tests don’t have bugs
and they test the right things. They don’t “cry wolf”
Maintablility - Developers will simply stop maintaining
and fixing tests that takes too long to change
3 Pillars of Good3 Pillars of Good
Unit TestUnit Test
Trustworthiness - trustworthy tests don’t have bugs
and they test the right things. They don’t “cry wolf”
Maintablility - Developers will simply stop maintaining
and fixing tests that takes too long to change
Readability - this means not just be able to read tests
but also figuring out the problem if tests seems to be
wrong. Without readability, other 2 pillars fall pretty
quickly.
3 Pillars of Good3 Pillars of Good
Unit TestUnit Test
Spock FrameworkSpock Framework
Leverage Groovy
Spock FrameworkSpock Framework
Leverage Groovy
Expressive testing language
Easy to Learn
Reduce the line of test code
Productivity
Structural blocks - BDD style -context, stimulus,
expectation
First SpecFirst Spec
import spock.lang.Specification
class GivenWhenThenSpec extends Specification {
def "test adding a new item to a set"() {
given:
def bag = [4, 6, 3, 2] as Set
when:
bag << 1
then:
bag.size() == 5
Feature methodFeature method
// feature method
def “test adding a new item to a set” () {
// block goes here
}
heart of spec
Four phases
setup the features fixture
provide stimulus to the system
describe the response
clean up
BlocksBlocks
given: precondition, data fixture
when: actions that trigger some outcome
then: makes assertions about outcode
expect: short alt to when & then
where: applies varied inputs
setup: alias for given
and: sub-divided other blocks
cleanup: post-condition, cleanup
CP Platform DemoCP Platform Demo
UserTacticRepository.java - method findByUid(String
uid)
Mock and InteractionMock and Interaction
verificationverification
Spock has build-in support for mocking
Subscriber sub=Mock() or
def sub=Mock(Subscriber)
DSL for specifying interaction
2 * sub.receive(“msg”)
CP DEMO InteractionCP DEMO Interaction
EventController - captureEvent (Tactic dismissal for
IPP event)
Test class EventControllerTest
1 * userTacticRepository.deactivateTactic(_,_,_)
StabbingStabbing
Implementations can be stabbed out easily
• EmailSender sender=Mock()
• String send(String msg) {.... }
• sender.send(_) >> “ok”
CP Demo StabbingCP Demo Stabbing
EventServiceImpl - getTargetListByUid and Event
ServiceTest
stabbing - targetListRepository.findByUid(_) >> users
Testing exceptionsTesting exceptions
testing code that throws exceptions
• when:
• someBadMethod()
• then:
• def exception=thrown(IllegalStateException)
• exception.message==”bad exception”
CP Demo - ExceptionsCP Demo - Exceptions
Event Controller Test - sending incomplete event
object and expect IncorrectEventException be
thrown
• then: ‘Exception is thrown’
•thrown (IncorrectEventException)
Spring IntegrationSpring Integration
• @ContextConfiguration([classpath:app-config.xml])
• @Autowired
• demo
HTTP callsHTTP calls
• For Spring apps – use Spring REST Template
• For others – use Groovy HTTP Builder or Selenium
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ){
uri.path = '/ajax/services/search/web'
uri.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}“
}
}
Spock datatablesSpock datatables
Spock data pipesSpock data pipes
There is moreThere is more
@Fast - @Slow
@AutoCleanUp - clean up/close resources
Async testing support
Data Driven for parametirized tests
Get it from Maven Central 07-groovy-2.0
https://code.google.com/p/spock/
Comprehensive ApproachComprehensive Approach
to Improve Qualityto Improve Quality
Automated Unit Tests
Automated Acceptance Test
Continuous Integration
Code quality analysis
Measurable values: number of defects and rework
Continuous IntegrationContinuous Integration
PipelinePipeline
Action PlanAction Plan
• Install Spock and Groovy
• Write test to cover existing BUG
• Write test as you write more code

Unit testing with Spock Framework

  • 1.
  • 2.
    AgendaAgenda Three qualities ofgood unit test Introduction to Spock Spock Idioms Mocks and Stubs Continuous Integration Pipeline Code coverage analysis
  • 3.
    Why Unit testsWhyUnit tests • Catch mistakes and avoid reworks Another production issue
  • 4.
    Why Unit testsWhyUnit tests • Shape design of our code
  • 5.
    Why Unit testsWhyUnit tests •Increased Productivity (shipped product) •Cheaper to solve problems
  • 6.
    Trustworthiness - trustworthytests don’t have bugs and they test the right things. They don’t “cry wolf” 3 Pillars of Good3 Pillars of Good Unit TestUnit Test
  • 7.
    Trustworthiness - trustworthytests don’t have bugs and they test the right things. They don’t “cry wolf” Maintablility - Developers will simply stop maintaining and fixing tests that takes too long to change 3 Pillars of Good3 Pillars of Good Unit TestUnit Test
  • 8.
    Trustworthiness - trustworthytests don’t have bugs and they test the right things. They don’t “cry wolf” Maintablility - Developers will simply stop maintaining and fixing tests that takes too long to change Readability - this means not just be able to read tests but also figuring out the problem if tests seems to be wrong. Without readability, other 2 pillars fall pretty quickly. 3 Pillars of Good3 Pillars of Good Unit TestUnit Test
  • 9.
  • 10.
    Spock FrameworkSpock Framework LeverageGroovy Expressive testing language Easy to Learn Reduce the line of test code Productivity Structural blocks - BDD style -context, stimulus, expectation
  • 11.
    First SpecFirst Spec importspock.lang.Specification class GivenWhenThenSpec extends Specification { def "test adding a new item to a set"() { given: def bag = [4, 6, 3, 2] as Set when: bag << 1 then: bag.size() == 5
  • 12.
    Feature methodFeature method //feature method def “test adding a new item to a set” () { // block goes here } heart of spec Four phases setup the features fixture provide stimulus to the system describe the response clean up
  • 13.
    BlocksBlocks given: precondition, datafixture when: actions that trigger some outcome then: makes assertions about outcode expect: short alt to when & then where: applies varied inputs setup: alias for given and: sub-divided other blocks cleanup: post-condition, cleanup
  • 14.
    CP Platform DemoCPPlatform Demo UserTacticRepository.java - method findByUid(String uid)
  • 15.
    Mock and InteractionMockand Interaction verificationverification Spock has build-in support for mocking Subscriber sub=Mock() or def sub=Mock(Subscriber) DSL for specifying interaction 2 * sub.receive(“msg”)
  • 16.
    CP DEMO InteractionCPDEMO Interaction EventController - captureEvent (Tactic dismissal for IPP event) Test class EventControllerTest 1 * userTacticRepository.deactivateTactic(_,_,_)
  • 17.
    StabbingStabbing Implementations can bestabbed out easily • EmailSender sender=Mock() • String send(String msg) {.... } • sender.send(_) >> “ok”
  • 18.
    CP Demo StabbingCPDemo Stabbing EventServiceImpl - getTargetListByUid and Event ServiceTest stabbing - targetListRepository.findByUid(_) >> users
  • 19.
    Testing exceptionsTesting exceptions testingcode that throws exceptions • when: • someBadMethod() • then: • def exception=thrown(IllegalStateException) • exception.message==”bad exception”
  • 20.
    CP Demo -ExceptionsCP Demo - Exceptions Event Controller Test - sending incomplete event object and expect IncorrectEventException be thrown • then: ‘Exception is thrown’ •thrown (IncorrectEventException)
  • 21.
    Spring IntegrationSpring Integration •@ContextConfiguration([classpath:app-config.xml]) • @Autowired • demo
  • 22.
    HTTP callsHTTP calls •For Spring apps – use Spring REST Template • For others – use Groovy HTTP Builder or Selenium def http = new HTTPBuilder( 'http://ajax.googleapis.com' ) // perform a GET request, expecting JSON response data http.request( GET, JSON ){ uri.path = '/ajax/services/search/web' uri.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.
  • 24.
  • 25.
    There is moreThereis more @Fast - @Slow @AutoCleanUp - clean up/close resources Async testing support Data Driven for parametirized tests Get it from Maven Central 07-groovy-2.0 https://code.google.com/p/spock/
  • 26.
    Comprehensive ApproachComprehensive Approach toImprove Qualityto Improve Quality Automated Unit Tests Automated Acceptance Test Continuous Integration Code quality analysis Measurable values: number of defects and rework
  • 27.
  • 28.
    Action PlanAction Plan •Install Spock and Groovy • Write test to cover existing BUG • Write test as you write more code