SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPT
Spock Framework
Леонид Ставила
 
ODP
Grails unit testing
pleeps
 
PPT
Spock
Gajraj Kalburgi
 
PPTX
Automation patterns on practice
automated-testing.info
 
PPTX
Spock
Evgeny Borisov
 
PPT
Ggug spock
Skills Matter
 
PPTX
J unit스터디슬라이드
ksain
 
PPTX
Building unit tests correctly
Dror Helper
 
PPTX
Unit testing patterns for concurrent code
Dror Helper
 
PDF
Celery
Òscar Vilaplana
 
PDF
Python testing using mock and pytest
Suraj Deshmukh
 
PPT
jUnit
sundar22in
 
PPT
Google mock for dummies
Harry Potter
 
PDF
Modern Python Testing
Alexander Loechel
 
PPT
Introduzione al TDD
Andrea Francia
 
PDF
Writing good unit test
Lucy Lu
 
PPT
20111018 boost and gtest
Will Shen
 
KEY
Inside PyMongo - MongoNYC
Mike Dirolf
 
PPTX
TDD Training
Manuela Grindei
 
PPT
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
Grails unit testing
pleeps
 
Automation patterns on practice
automated-testing.info
 
Ggug spock
Skills Matter
 
J unit스터디슬라이드
ksain
 
Building unit tests correctly
Dror Helper
 
Unit testing patterns for concurrent code
Dror Helper
 
Python testing using mock and pytest
Suraj Deshmukh
 
jUnit
sundar22in
 
Google mock for dummies
Harry Potter
 
Modern Python Testing
Alexander Loechel
 
Introduzione al TDD
Andrea Francia
 
Writing good unit test
Lucy Lu
 
20111018 boost and gtest
Will Shen
 
Inside PyMongo - MongoNYC
Mike Dirolf
 
TDD Training
Manuela Grindei
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 

Viewers also liked (10)

PDF
VirtualJUG24 - Testing with Spock: The logical choice
Iván López Martín
 
PPT
Spock Framework 2
Ismael
 
PPT
Groovier testing with Spock
Robert Fletcher
 
PDF
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Iván López Martín
 
PDF
Taming Functional Web Testing with Spock and Geb
C4Media
 
PPT
Testing Storm components with Groovy and Spock
Eugene Dvorkin
 
PDF
A Gentle Introduction To Docker And All Things Containers
Jérôme Petazzoni
 
PDF
Docker by Example - Basics
Ganesh Samarthyam
 
PDF
UX, ethnography and possibilities: for Libraries, Museums and Archives
Ned Potter
 
PDF
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
VirtualJUG24 - Testing with Spock: The logical choice
Iván López Martín
 
Spock Framework 2
Ismael
 
Groovier testing with Spock
Robert Fletcher
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Iván López Martín
 
Taming Functional Web Testing with Spock and Geb
C4Media
 
Testing Storm components with Groovy and Spock
Eugene Dvorkin
 
A Gentle Introduction To Docker And All Things Containers
Jérôme Petazzoni
 
Docker by Example - Basics
Ganesh Samarthyam
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
Ned Potter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
Drift
 
Ad

Similar to Unit testing with Spock Framework (20)

PPTX
Grails Spock Testing
TO THE NEW | Technology
 
PPTX
Unit testing
NexThoughts Technologies
 
PDF
Spock-Framework: The Logical Choice for Modern Testing
Inexture Solutions
 
PDF
Unit test-using-spock in Grails
NexThoughts Technologies
 
PDF
Spock pres
elizhender
 
PDF
Cool JVM Tools to Help You Test
Schalk Cronjé
 
PDF
Spock
Naiyer Asif
 
PDF
Spocktacular testing
Russel Winder
 
PDF
Spock Testing Framework
Amir Langer
 
PDF
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Schalk Cronjé
 
PDF
Spocktacular Testing
Russel Winder
 
PDF
Spocktacular Testing - Russel Winder
JAXLondon2014
 
PDF
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Kevin Brockhoff
 
PDF
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
PDF
Codemotion 2015 spock_workshop
Fernando Redondo Ramírez
 
PPTX
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
Yaroslav Yermilov
 
PDF
Unit testing - A&BP CC
JWORKS powered by Ordina
 
PPTX
Testing in Scala by Adform research
Vasil Remeniuk
 
PPTX
Testing in Scala. Adform Research
Vasil Remeniuk
 
PDF
Spring IO 2015 Spock Workshop
Fernando Redondo Ramírez
 
Grails Spock Testing
TO THE NEW | Technology
 
Spock-Framework: The Logical Choice for Modern Testing
Inexture Solutions
 
Unit test-using-spock in Grails
NexThoughts Technologies
 
Spock pres
elizhender
 
Cool JVM Tools to Help You Test
Schalk Cronjé
 
Spocktacular testing
Russel Winder
 
Spock Testing Framework
Amir Langer
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Schalk Cronjé
 
Spocktacular Testing
Russel Winder
 
Spocktacular Testing - Russel Winder
JAXLondon2014
 
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Kevin Brockhoff
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
Christian Baranowski
 
Codemotion 2015 spock_workshop
Fernando Redondo Ramírez
 
What Mr. Spock would possibly say about modern unit testing: pragmatic and em...
Yaroslav Yermilov
 
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Testing in Scala by Adform research
Vasil Remeniuk
 
Testing in Scala. Adform Research
Vasil Remeniuk
 
Spring IO 2015 Spock Workshop
Fernando Redondo Ramírez
 
Ad

Recently uploaded (20)

PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 

Unit testing with Spock Framework

  • 2. AgendaAgenda Three qualities of good unit test Introduction to Spock Spock Idioms Mocks and Stubs Continuous Integration Pipeline Code coverage analysis
  • 3. Why Unit testsWhy Unit tests • Catch mistakes and avoid reworks Another production issue
  • 4. Why Unit testsWhy Unit tests • Shape design of our code
  • 5. Why Unit testsWhy Unit tests •Increased Productivity (shipped product) •Cheaper to solve problems
  • 6. 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
  • 7. 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
  • 8. 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
  • 10. 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
  • 11. 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
  • 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, 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
  • 14. CP Platform DemoCP Platform Demo UserTacticRepository.java - method findByUid(String uid)
  • 15. 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”)
  • 16. CP DEMO InteractionCP DEMO Interaction EventController - captureEvent (Tactic dismissal for IPP event) Test class EventControllerTest 1 * userTacticRepository.deactivateTactic(_,_,_)
  • 17. StabbingStabbing Implementations can be stabbed out easily • EmailSender sender=Mock() • String send(String msg) {.... } • sender.send(_) >> “ok”
  • 18. CP Demo StabbingCP Demo Stabbing EventServiceImpl - getTargetListByUid and Event ServiceTest stabbing - targetListRepository.findByUid(_) >> users
  • 19. Testing exceptionsTesting exceptions testing code 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}“ } }
  • 24. Spock data pipesSpock data pipes
  • 25. 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/
  • 26. 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
  • 28. Action PlanAction Plan • Install Spock and Groovy • Write test to cover existing BUG • Write test as you write more code