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

PDF
Spock Framework
PDF
Spock: Test Well and Prosper
PPTX
Smarter Testing With Spock
PDF
Java Testing With Spock - Ken Sipe (Trexin Consulting)
PDF
Spock Testing Framework - The Next Generation
PPTX
Smarter Testing with Spock
PDF
Spock framework
PPTX
Unit/Integration Testing using Spock
Spock Framework
Spock: Test Well and Prosper
Smarter Testing With Spock
Java Testing With Spock - Ken Sipe (Trexin Consulting)
Spock Testing Framework - The Next Generation
Smarter Testing with Spock
Spock framework
Unit/Integration Testing using Spock

What's hot (20)

PPT
ODP
Grails unit testing
PPT
PPTX
Automation patterns on practice
PPTX
PPT
Ggug spock
PPTX
J unit스터디슬라이드
PPTX
Building unit tests correctly
PPTX
Unit testing patterns for concurrent code
PDF
PDF
Python testing using mock and pytest
PPT
jUnit
PPT
Google mock for dummies
PDF
Modern Python Testing
PPT
Introduzione al TDD
PDF
Writing good unit test
PPT
20111018 boost and gtest
KEY
Inside PyMongo - MongoNYC
PPTX
TDD Training
PPT
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Grails unit testing
Automation patterns on practice
Ggug spock
J unit스터디슬라이드
Building unit tests correctly
Unit testing patterns for concurrent code
Python testing using mock and pytest
jUnit
Google mock for dummies
Modern Python Testing
Introduzione al TDD
Writing good unit test
20111018 boost and gtest
Inside PyMongo - MongoNYC
TDD Training
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Ad

Viewers also liked (10)

PDF
VirtualJUG24 - Testing with Spock: The logical choice
PPT
Spock Framework 2
PPT
Groovier testing with Spock
PDF
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
PDF
Taming Functional Web Testing with Spock and Geb
PPT
Testing Storm components with Groovy and Spock
PDF
A Gentle Introduction To Docker And All Things Containers
PDF
Docker by Example - Basics
PDF
UX, ethnography and possibilities: for Libraries, Museums and Archives
PDF
3 Things Every Sales Team Needs to Be Thinking About in 2017
VirtualJUG24 - Testing with Spock: The logical choice
Spock Framework 2
Groovier testing with Spock
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Taming Functional Web Testing with Spock and Geb
Testing Storm components with Groovy and Spock
A Gentle Introduction To Docker And All Things Containers
Docker by Example - Basics
UX, ethnography and possibilities: for Libraries, Museums and Archives
3 Things Every Sales Team Needs to Be Thinking About in 2017
Ad

Similar to Unit testing with Spock Framework (20)

PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
PDF
Javascript tdd byandreapaciolla
PPTX
Whitebox testing of Spring Boot applications
KEY
Testing w-mocks
PPT
Unit testing php-unit - phing - selenium_v2
PDF
Web Services Automated Testing via SoapUI Tool
PPTX
Java script unit testing
PDF
Unit Testing - The Whys, Whens and Hows
PDF
Developers Testing - Girl Code at bloomon
PPTX
Junit_.pptx
PDF
Quick tour to front end unit testing using jasmine
PDF
The Many Ways to Test Your React App
PPTX
Principles and patterns for test driven development
PDF
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
PDF
TDD super mondays-june-2014
PPTX
unit test in node js - test cases in node
PDF
Testing Angular
PDF
Advanced Java Testing
PPTX
Full Stack Unit Testing
PPT
Assessing Unit Test Quality
We Are All Testers Now: The Testing Pyramid and Front-End Development
Javascript tdd byandreapaciolla
Whitebox testing of Spring Boot applications
Testing w-mocks
Unit testing php-unit - phing - selenium_v2
Web Services Automated Testing via SoapUI Tool
Java script unit testing
Unit Testing - The Whys, Whens and Hows
Developers Testing - Girl Code at bloomon
Junit_.pptx
Quick tour to front end unit testing using jasmine
The Many Ways to Test Your React App
Principles and patterns for test driven development
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
TDD super mondays-june-2014
unit test in node js - test cases in node
Testing Angular
Advanced Java Testing
Full Stack Unit Testing
Assessing Unit Test Quality

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Spectroscopy.pptx food analysis technology
PPTX
A Presentation on Artificial Intelligence
PPTX
1. Introduction to Computer Programming.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
cuic standard and advanced reporting.pdf
PPTX
Tartificialntelligence_presentation.pptx
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Spectroscopy.pptx food analysis technology
A Presentation on Artificial Intelligence
1. Introduction to Computer Programming.pptx
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Machine Learning_overview_presentation.pptx
Electronic commerce courselecture one. Pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Approach and Philosophy of On baking technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
A comparative analysis of optical character recognition models for extracting...
cuic standard and advanced reporting.pdf
Tartificialntelligence_presentation.pptx

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