SlideShare une entreprise Scribd logo
1  sur  28
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

Contenu connexe

Tendances

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit testLucy Lu
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 

Tendances (20)

Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Spock
SpockSpock
Spock
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Spock
SpockSpock
Spock
 
Ggug spock
Ggug spockGgug spock
Ggug spock
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Celery
CeleryCelery
Celery
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
jUnit
jUnitjUnit
jUnit
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 

En vedette

VirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceVirtualJUG24 - Testing with Spock: The logical choice
VirtualJUG24 - Testing with Spock: The logical choiceIván López Martín
 
Spock Framework 2
Spock Framework 2Spock Framework 2
Spock Framework 2Ismael
 
Groovier testing with Spock
Groovier testing with SpockGroovier testing with Spock
Groovier testing with SpockRobert Fletcher
 
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...Madrid GUG 2016 (Alicante) - Spock: O por qué deberías utilizarlo para testea...
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
Taming Functional Web Testing with Spock and GebTaming Functional Web Testing with Spock and Geb
Taming Functional Web Testing with Spock and GebC4Media
 
Testing Storm components with Groovy and Spock
Testing Storm components with Groovy and SpockTesting Storm components with Groovy and Spock
Testing Storm components with Groovy and SpockEugene Dvorkin
 
A Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersA Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersJérôme Petazzoni
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 

En vedette (10)

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

Similaire à Unit Testing with Spock Framework

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Web Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolWeb Services Automated Testing via SoapUI Tool
Web Services Automated Testing via SoapUI ToolSperasoft
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't SuckDeliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't SuckKevin Brockhoff
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014Alex Kavanagh
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in nodeGoa App
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 

Similaire à Unit Testing with Spock Framework (20)

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

Dernier

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Dernier (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

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