SlideShare ist ein Scribd-Unternehmen logo
1 von 71
© 2015 McW est Corporation
Spock TDD
Tests as Assets not Afterthoughts
by Brian Westrich, McWest Corp.
bw@mcwest.com
1
© 2015 McW est Corporation
About me
• TDD developer since 1989
• Minneapolis-based
• Consultant at McWest Corp. (www.mcwest.com)
• Custom software design, development,
and mentoring
• Historical focus: Java/Groovy
• Increasing focus: JavaScript
• Recently consulted for large enterprise successfully using TDD
© 2015 McW est Corporation
Minneapolis development projects:
Light-rail, Vikings stadium
© 2015 McW est Corporation
Agenda
• History of TDD
• Spock TDD case study
• Spock tests as assets
• Testing effectively
• TDD in teams
• TDD mantras
• Summary / Conclusion
• Resources
4
© 2015 McW est Corporation
History of TDD
5
© 2015 McW est Corporation 6
Timeframe? Automated dev tests are Developers say
Pre - 2000 a curiousity “Why is he testing?”
Early 2000s a threat “Don’t check that in.”
Mid 2000s a given “Good idea!”
Late 2000s an obsession “We need 100% coverage.”
2010 - now an obligation, an afterthought
“I’ve finished everything except
the tests.”
Future? an asset?
“My project needs tests, and I
want to write them.”
© 2015 McW est Corporation
Presentation Goal
• Help you create tests that are Assets not Afterthoughts.
• Make you want to spend more time writing tests.
7
© 2015 McW est Corporation
Survey
• 60 attendees (room nearly full)
• Development languages
• Java (all), Groovy (all), scala (none), clojure (none), JavaScript(10), other
• Testing tools
• Junit (all), TestNG(2), Spock (most), other
• OS (development)
• Mac (1/4), Windows (2/3), Linux (handful)
• IDE
• IntelliJ (1/2), STS (4), Bare eclipse (1), Sublime (1), emacs, nano, vi, other
• TDD (3)
8
© 2015 McW est Corporation
Spock TDD Case Study
9
© 2015 McW est Corporation
Calculating Calories from Proximates
• Calories =
4 * carbs +
9 * fat +
4 * protein +
7 * alcohol
10
© 2015 McW est Corporation
Additional requirement: Missing proximates
• Don’t calculate calories if we don’t have proximate values
11
© 2015 McW est Corporation
Problem
• Calories aren’t calculating for most of our foods
New Requirement:
If alcohol value is missing, assume it is zero
12
© 2015 McW est Corporation
New requirement: Missing ingredient values
• If ingredients are missing one or more proximate values, flag the calorie value
as having missing ingredient values
13
© 2015 McW est Corporation
New requirement: Ingredient missing alcohol
• If alcohol is missing in one of the ingredients, don’t flag the calorie value as
having missing ingredient values.
14
© 2015 McW est Corporation
Initial algorithm Final algorithm
15
Case Study Takeaway:
Functionality starts simple, becomes complicated
© 2015 McW est Corporation
With specs…
• Implementation can be
refactored, is
maintainable, and is
documented
Without specs…
• Implementation becomes
unmaintainable (imagine
first implementation
patched to implement final
implementation) and
undocumented
16
Case Study Takeaway
© 2015 McW est Corporation
Case Study Takeaway: Reflections
• Is the final where table too large?
• If so, how would you break it into smaller tables?
• Extra credit: if you break the test up, what new test(s) might you introduce to
show how all requirements relate to each other?
17
© 2015 McW est Corporation
Spock TDD Case Study
18
https://github.com/bwestrich/tdd-spock/blob/master/src/test/groovy
/mcwest/casestudies/calories/README.md
© 2015 McW est Corporation
TDD Benefits and Costs
• Benefits
• Immediate developer feedback
• Improves design
• Documents system
• Allows safe refactoring
• Costs
• Time to write tests
• Time to run tests
• Harder to refactor?
19
© 2015 McW est Corporation
Spock Tests as Assets
20
© 2015 McW est Corporation
What I’ll cover on Spock in next section
• Spock best practices
• Not an intro to Spock
• Not a comprehensive review of all Spock’s features
• Spock code examples most useful if you have a basic knowledge of Spock or
mocking/stubbing
• For a Spock overview, see Spock references listed at
https://github.com/bwestrich/tdd-spock
21
© 2015 McW est Corporation
Spock Tests as Assets:
Best practices, with code examples
• Name methods well (NamingTestsSpec)
• Use behavioral syntax (UseGivenNotSetupSpec)
• Comments on blocks (optional) (UseGivenNotSetupSpec)
• Emphasize typical cases (SpecifyClassUnderTestSpec)
• Put expected values at end of tables (SpecifyClassUnderTestSpec)
• Use double vertical bars to highlight results (SpecifyClassUnderTestSpec)
• Use comments and @Unroll in tables (SpecifyClassUnderTestSpec)
• Avoid double trouble (StubsAndMocksSpec)
• Fix broken tests (VaCalculateCaloriesFunctionalSpec)
• Limit size of tables (SmallerWhereSpec)
* class names (camel case capital letters)
22
© 2015 McW est Corporation
Spock Tests as Assets
https://github.com/bwestrich/tdd-spock/blob/master/README.md
23
© 2015 McW est Corporation
Testing Effectively
24
© 2015 McW est Corporation
Testing effectively
• Types of tests
• Finding tests
• Writing tests
• Running tests
• Testing before committing
25
© 2015 McW est Corporation
Types of (automated) tests
26
Type What it tests Spock support Comment
Functional
how system works from
“user’s” perspective
Geb
Most important
Lowest coverage
Unit details mocks/stubs
Fast, fun
Highest coverage
Integration how details work together
controller web
tests*
Usage varies for
different projects
Smoke deployments Geb Spot check
* https://github.com/bwestrich/tdd-spock/blob/master/README-MOCKMVC.md
© 2015 McW est Corporation
Spock uses same syntax for all test types
27
© 2015 McW est Corporation
Red Green Clean
28
1. Write
new or
break
existing
test
2. Fix
test
3. Clean
(refactor)
© 2015 McW est Corporation
Don’t trust a test that hasn’t failed
-- Kevin Beatty
29
© 2015 McW est Corporation
Using test types: Unit First
1. Write/break unit test
2. Fix unit test
3. Clean test code and tested code
4. Write/break integration test (optional)
5. Fix integration test
6. Clean test code and tested code
7. Write/break functional test (optional)
8. Fix functional test
9. Clean test code and tested code
30
© 2015 McW est Corporation
Using test types: Functional First
1. Write/break functional test (optional)
2. Write/break integration test (optional)
3. Write/break unit test
4. Fix unit test
5. Clean test code and tested code
6. Fix integration test
7. Clean test code and tested code
8. Fix functional test
9. Clean test code and tested code
31
© 2015 McW est Corporation
Order of Test Types for Different Tasks
Task Usual Approach Note
Defect fix FF Developer-reported
defects might use UF
New feature (tools and
requirements well
understood)
UF Business requested? FF
New feature (when
learning technology or
requirements)
Whatever approach
works (even writing code
before tests!)
Feature is not complete
until tests pass and
refactoring complete
32
Legend: FF = Functional First, UF = Unit First
© 2015 McW est Corporation
Write tests as soon as possible
• The sooner you write tests, the better they can help guide your design
• OK: write code, then (before pushing) test code
• Better: write tests while you write the tested code
• Best: write tests before the tested code.
o Added benefit: verify the test fails before feature written / defect fixed
(don’t trust a test that hasn’t failed)
33
© 2015 McW est Corporation
Different projects use different test types
Test type Run duration When run
Unit < 1 minute Constantly while coding,
pre-push
Integration 10 minutes Pre-push
Functional None n/a
34
Project:
Provide website content for nationwide electronics retailer,
no front-end development done by our team.
© 2015 McW est Corporation
Different projects use different test types
Test type Run duration When run
Unit < 1 minute Constantly while coding,
pre-push
Integration 1 minute Occasionally while
coding, pre-push
Functional 10 minutes Pre-push
35
Project:
Departmental app, full-stack development.
© 2015 McW est Corporation
Reliable integration and functional tests
• Don’t tolerate “false positives”
• Tests that fail for any reason other than defective software
• Decrease value of your tests
• “Fix broken windows”
• Tips on avoiding “false positives”
• @Stepwise
• Manage your test data
• Extend Geb as needed
36
© 2015 McW est Corporation
Use @Stepwise
to guarantee run method order
37
© 2015 McW est Corporation
Manage your test data
• Script it!
• SQL, DBUnit, etc.
• Periodically refresh all data in test environments
• Reserve ranges for testing
• ID numbers (negative IDs? Large IDs?)
• Code values
• Other special “marking”
• Tests should not change shared data (allows concurrent test runs)
38
© 2015 McW est Corporation
Geb testing of asynchronous JavaScript
• Using angular? Try ng-busy to manage asynchronous processing
• Use ng-busy to display a ‘Processing’ message to users while waiting for
any http server requests, have tests wait when label is displayed
Page object method
Example code in test
39
© 2015 McW est Corporation
Using test types: Takeaway
• All types of tests are an integral part of development
• Use the correct test type for the job at hand
• Use test types that fit your project
• Write tests as soon as possible
• Prevent false-positives
• And, of course….. ;-)
• Run ALL test types before pushing changes
40
© 2015 McW est Corporation
Keyboard shortcuts
• Learn and use them! (pairing?)
• OS and IDE specific
• OS: Mac, Linux, Windows
• IDE: IntelliJ, Eclipse, nano, emacs, vi, …….
• This presentation uses Mac (OSX) and IntelliJ 14.1.4
41
© 2015 McW est Corporation
Finding Tests
• Test location
• As close to Class Under Test as possible
• Same project, package, name prefix (MyClass and MyClassSpec)
• Different source folder
• Keyboard shortcuts (DEMO)
• Toggle between class and test: Cmd-Shift-T
• Find by name: Cmd-Shift-O
o (type caps to exploit camel case, e.g. MCS finds MyClassSpec)
42
© 2015 McW est Corporation
Writing Tests
• Where table keyboard shortcuts (DEMO)
• Column editing
o Create
o Update
o Delete
• Column formatting: Cmd-Alt-L
43
© 2015 McW est Corporation
Running Tests (IDE)
• Keyboard shortcuts (DEMO)
• Ctrl-Shift-R: Run highlighted test
• Ctrl-R: Run previously run test
44
© 2015 McW est Corporation
Running Tests (command line)
• Create team aliases for common operations for your team’s languages /
frameworks / build systems
• Operations
o refresh dependencies, clean, test, run
• Languages / frameworks: build systems
o JavaScript/Angular: grunt, gulp
o Java/Groovy/Spring Boot: maven, gradle
45
© 2015 McW est Corporation
Running tests command line (DEMO)
46
© 2015 McW est Corporation
Running Tests (command line) (cont.)
• Team aliases
• Add to source control
• Add directory to execution path
• Provide easy ways for team to update (“ea”, “listaliases”)
• Basic example: https://github.com/mcwest/team-aliases
• Supports:
47
© 2015 McW est Corporation
Test Before Pushing
• The right way: Run all tests (of all types) before pushing (to source control)
• Why it’s hard to do:
• Commands to run tests are arcane, inconsistent, error prone
• Tests take long time to run
• Tests fail after running long time (waste of time!)
• Results hard to find/interpret (just say ‘ok’ or ‘not’)
• While waiting, you can’t do ANYTHING else
• How to make the right way easy?
48
© 2015 McW est Corporation
Asynchronous pre-push testing (via script)
• Call script something short: e.g. “go”
• What script does
• Cleans and builds all components in separate workspace
• Runs ALL unit/integration/functional tests and code style checkers
• Fails fast (slow tests run last)
• Runs in background
o Spawns separate instance of components with dedicated resources
(workspace, ports, data, log files, …)
o Audio notification of results (have some fun here!)
• Manage same as a team alias (in source control, on execution path)
49
© 2015 McW est Corporation
Before svn commit
1. ‘go’, then if errors, fix and refactor
2. ‘svn update’
3. if changes, go back to step 1, otherwise ‘svn commit’
50
© 2015 McW est Corporation
Before git push
1. ‘go’, then if errors, fix and refactor
2. ‘git commit’
3. ‘git smart-pull’ (alias ‘gsp’)
4. if changes, go back to step 1, otherwise ‘git push’
• Notes:
• Step #2 makes git merges easier to manage by not mixing local changes and remote
changes into same commit
• Step #3 uses the excellent git smart-pull add-on, see
https://github.com/mcwest/team-aliases for more info
51
© 2015 McW est Corporation
Asynchronous pre-push testing (other methods)
• Team City (JetBrains): not out of the box, need to configure post-commit hook
• Other tools?
• Anyone have solutions to share to this?
52
© 2015 McW est Corporation
Testing effectively (review)
• Types of tests
• Finding tests
• Writing tests
• Running tests
• Testing before committing
53
© 2015 McW est Corporation
TDD in Teams
• Pair Programming
• Pull Requests
• Continuous Integration
• Continuous Deployment
54
© 2015 McW est Corporation
Pair Programming
• Wonderful way to learn, teach, enjoy TDD/Spock
• Very productive
• Roles
• Driver (shows new ways to find/write/run/commit tests)
• Observer (watches for typos, testing the right thing, next test type)
• Keep both members switching roles
• TDD ping pong: ping pong ping pong ping pong
• Other ideas?
• Cautions
• Team must want to pair (pre-interview question)
• Workspace must be conducive to pairing
55
© 2015 McW est Corporation
Pair Programming Workspace
56
© 2015 McW est Corporation
Pull Requests (PR)
• Great compliment to / replacement for pairing
• Does not require workspace re-config
• Works with remote teams (but can pair over skype/hangouts/…)
• More conducive to some developers’ workstyles than pairing
• TDD and PRs
• Submitter must include tests in the PR
• Reviewer should run tests in background (using ‘go’) while reviewing
• Cautions
• Requires understanding of source code branching
• Commands to create PR’s not trivial
o Set up command line aliases to streamline
57
© 2015 McW est Corporation
Continuous Integration
• Trigger build immediately on push (commit hooks preferred over polling)
• Notify team of broken builds
• Emails
• Texts
• IM/Slack?
• Make broken builds visible
• Radiator (Jenkins plugin)
58
© 2015 McW est Corporation
Continuous Deployment
• Impossible without automated tests
• TDD a great way (the only way) to build automated tests that verify a system at
all levels
59
© 2015 McW est Corporation
Test Mantras
Mantra -- “a statement or slogan repeated frequently”
• Test the right thing
• APIs not internals
• Don’t trust a test that hasn’t failed
• The right way easy
• Tests are assets not afterthoughts
60
© 2015 McW est Corporation
Spock: Specification at all levels
61
© 2015 McW est Corporation
From the smallest unit…
62
© 2015 McW est Corporation
… to detailed interactions …
63
© 2015 McW est Corporation
… to higher level interactions …
64
© 2015 McW est Corporation
… to the user’s view of the system.
65
© 2015 McW est Corporation
The needs of the many
outweigh the needs of the few.
66
© 2015 McW est Corporation
Conclusion
Using the techniques and approaches we’ve
discussed, automated developer-written tests
become less something we do as an afterthought (if
at all), and more an asset we demand on our future
projects.
67
© 2015 McW est Corporation
Resources
• Spock TDD: https://github.com/bwestrich/tdd-spock
• TDD cribsheet (JUnit oriented): https://bitbucket.org/bwestrich/java-tdd
• Command line aliases: https://github.com/mcwest/team-aliases
68
© 2015 McW est Corporation 69
Spock ‘seed art’ credit
© 2015 McW est Corporation
Minneapolis ‘seed art’ credit
70
© 2015 McW est Corporation
Spock TDD
Tests as Assets not Afterthoughts
by Brian Westrich, McWest Corp.
bw@mcwest.com
71

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Testing Java EE apps with Arquillian
Testing Java EE apps with ArquillianTesting Java EE apps with Arquillian
Testing Java EE apps with Arquillian
 
Testing for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into EverythingTesting for Agility: Bringing Testing into Everything
Testing for Agility: Bringing Testing into Everything
 
Selenium Users Anonymous
Selenium Users AnonymousSelenium Users Anonymous
Selenium Users Anonymous
 
The Fitnesse Fix
The Fitnesse FixThe Fitnesse Fix
The Fitnesse Fix
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
 
Brownie
BrownieBrownie
Brownie
 
Test management struggles and challenges in SDLC
Test management struggles and challenges in SDLCTest management struggles and challenges in SDLC
Test management struggles and challenges in SDLC
 
Agile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source FrameworksAgile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source Frameworks
 
Leandro Melendez - Switching Performance Left & Right
Leandro Melendez - Switching Performance Left & RightLeandro Melendez - Switching Performance Left & Right
Leandro Melendez - Switching Performance Left & Right
 
Model-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next LevelModel-based Testing: Taking BDD/ATDD to the Next Level
Model-based Testing: Taking BDD/ATDD to the Next Level
 
Selenium Frameworks
Selenium FrameworksSelenium Frameworks
Selenium Frameworks
 
Testing in TFS
Testing in TFSTesting in TFS
Testing in TFS
 
Thucydides – next generation acceptance testing with WebDriver
Thucydides – next generation acceptance testing with WebDriverThucydides – next generation acceptance testing with WebDriver
Thucydides – next generation acceptance testing with WebDriver
 
Battle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java ProjectBattle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java Project
 
Colorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestColorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latest
 
The limits of unit testing by Craig Stuntz
The limits of unit testing by Craig StuntzThe limits of unit testing by Craig Stuntz
The limits of unit testing by Craig Stuntz
 

Andere mochten auch

Andere mochten auch (9)

TDD with Spock @xpdays_ua
TDD with Spock @xpdays_uaTDD with Spock @xpdays_ua
TDD with Spock @xpdays_ua
 
Spock - the next stage of unit testing
Spock - the next stage of unit testingSpock - the next stage of unit testing
Spock - the next stage of unit testing
 
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
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
Geb with spock
Geb with spockGeb with spock
Geb with spock
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with Spock
 
Fabulous Tests on Spock and Groovy
Fabulous Tests on Spock and GroovyFabulous Tests on Spock and Groovy
Fabulous Tests on Spock and Groovy
 
Spock Extensions Anatomy
Spock Extensions AnatomySpock Extensions Anatomy
Spock Extensions Anatomy
 

Ähnlich wie Westrich spock-assets-gum

Ähnlich wie Westrich spock-assets-gum (20)

Adopting Agile
Adopting AgileAdopting Agile
Adopting Agile
 
Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
Agile testing
Agile testingAgile testing
Agile testing
 
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowMay 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
Continuous Delivery & Testing Madrid AfterTest
Continuous Delivery & Testing Madrid AfterTestContinuous Delivery & Testing Madrid AfterTest
Continuous Delivery & Testing Madrid AfterTest
 
Level Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit TestingLevel Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit Testing
 
Test automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application ServerTest automation lessons from WebSphere Application Server
Test automation lessons from WebSphere Application Server
 
Reaching for Your Quality Stretch Goals: Testing at Realtor.com
Reaching for Your Quality Stretch Goals: Testing at Realtor.comReaching for Your Quality Stretch Goals: Testing at Realtor.com
Reaching for Your Quality Stretch Goals: Testing at Realtor.com
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
Test driven development v1.0
Test driven development v1.0Test driven development v1.0
Test driven development v1.0
 
Agile Testing - What is it?
Agile Testing - What is it?Agile Testing - What is it?
Agile Testing - What is it?
 
Agile Testing
Agile Testing  Agile Testing
Agile Testing
 
Cpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp EuropeCpp Testing Techniques Tips and Tricks - Cpp Europe
Cpp Testing Techniques Tips and Tricks - Cpp Europe
 
Testlink Test Management with Teamforge
Testlink Test Management with TeamforgeTestlink Test Management with Teamforge
Testlink Test Management with Teamforge
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew Siemer
 
Small is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case DesignSmall is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case Design
 
Webinar: "5 semplici passi per migliorare la Quality e i processi di Test".
Webinar: "5 semplici passi per migliorare la Quality e i processi di Test".Webinar: "5 semplici passi per migliorare la Quality e i processi di Test".
Webinar: "5 semplici passi per migliorare la Quality e i processi di Test".
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and Beyond
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Kürzlich hochgeladen (20)

%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

Westrich spock-assets-gum

  • 1. © 2015 McW est Corporation Spock TDD Tests as Assets not Afterthoughts by Brian Westrich, McWest Corp. bw@mcwest.com 1
  • 2. © 2015 McW est Corporation About me • TDD developer since 1989 • Minneapolis-based • Consultant at McWest Corp. (www.mcwest.com) • Custom software design, development, and mentoring • Historical focus: Java/Groovy • Increasing focus: JavaScript • Recently consulted for large enterprise successfully using TDD
  • 3. © 2015 McW est Corporation Minneapolis development projects: Light-rail, Vikings stadium
  • 4. © 2015 McW est Corporation Agenda • History of TDD • Spock TDD case study • Spock tests as assets • Testing effectively • TDD in teams • TDD mantras • Summary / Conclusion • Resources 4
  • 5. © 2015 McW est Corporation History of TDD 5
  • 6. © 2015 McW est Corporation 6 Timeframe? Automated dev tests are Developers say Pre - 2000 a curiousity “Why is he testing?” Early 2000s a threat “Don’t check that in.” Mid 2000s a given “Good idea!” Late 2000s an obsession “We need 100% coverage.” 2010 - now an obligation, an afterthought “I’ve finished everything except the tests.” Future? an asset? “My project needs tests, and I want to write them.”
  • 7. © 2015 McW est Corporation Presentation Goal • Help you create tests that are Assets not Afterthoughts. • Make you want to spend more time writing tests. 7
  • 8. © 2015 McW est Corporation Survey • 60 attendees (room nearly full) • Development languages • Java (all), Groovy (all), scala (none), clojure (none), JavaScript(10), other • Testing tools • Junit (all), TestNG(2), Spock (most), other • OS (development) • Mac (1/4), Windows (2/3), Linux (handful) • IDE • IntelliJ (1/2), STS (4), Bare eclipse (1), Sublime (1), emacs, nano, vi, other • TDD (3) 8
  • 9. © 2015 McW est Corporation Spock TDD Case Study 9
  • 10. © 2015 McW est Corporation Calculating Calories from Proximates • Calories = 4 * carbs + 9 * fat + 4 * protein + 7 * alcohol 10
  • 11. © 2015 McW est Corporation Additional requirement: Missing proximates • Don’t calculate calories if we don’t have proximate values 11
  • 12. © 2015 McW est Corporation Problem • Calories aren’t calculating for most of our foods New Requirement: If alcohol value is missing, assume it is zero 12
  • 13. © 2015 McW est Corporation New requirement: Missing ingredient values • If ingredients are missing one or more proximate values, flag the calorie value as having missing ingredient values 13
  • 14. © 2015 McW est Corporation New requirement: Ingredient missing alcohol • If alcohol is missing in one of the ingredients, don’t flag the calorie value as having missing ingredient values. 14
  • 15. © 2015 McW est Corporation Initial algorithm Final algorithm 15 Case Study Takeaway: Functionality starts simple, becomes complicated
  • 16. © 2015 McW est Corporation With specs… • Implementation can be refactored, is maintainable, and is documented Without specs… • Implementation becomes unmaintainable (imagine first implementation patched to implement final implementation) and undocumented 16 Case Study Takeaway
  • 17. © 2015 McW est Corporation Case Study Takeaway: Reflections • Is the final where table too large? • If so, how would you break it into smaller tables? • Extra credit: if you break the test up, what new test(s) might you introduce to show how all requirements relate to each other? 17
  • 18. © 2015 McW est Corporation Spock TDD Case Study 18 https://github.com/bwestrich/tdd-spock/blob/master/src/test/groovy /mcwest/casestudies/calories/README.md
  • 19. © 2015 McW est Corporation TDD Benefits and Costs • Benefits • Immediate developer feedback • Improves design • Documents system • Allows safe refactoring • Costs • Time to write tests • Time to run tests • Harder to refactor? 19
  • 20. © 2015 McW est Corporation Spock Tests as Assets 20
  • 21. © 2015 McW est Corporation What I’ll cover on Spock in next section • Spock best practices • Not an intro to Spock • Not a comprehensive review of all Spock’s features • Spock code examples most useful if you have a basic knowledge of Spock or mocking/stubbing • For a Spock overview, see Spock references listed at https://github.com/bwestrich/tdd-spock 21
  • 22. © 2015 McW est Corporation Spock Tests as Assets: Best practices, with code examples • Name methods well (NamingTestsSpec) • Use behavioral syntax (UseGivenNotSetupSpec) • Comments on blocks (optional) (UseGivenNotSetupSpec) • Emphasize typical cases (SpecifyClassUnderTestSpec) • Put expected values at end of tables (SpecifyClassUnderTestSpec) • Use double vertical bars to highlight results (SpecifyClassUnderTestSpec) • Use comments and @Unroll in tables (SpecifyClassUnderTestSpec) • Avoid double trouble (StubsAndMocksSpec) • Fix broken tests (VaCalculateCaloriesFunctionalSpec) • Limit size of tables (SmallerWhereSpec) * class names (camel case capital letters) 22
  • 23. © 2015 McW est Corporation Spock Tests as Assets https://github.com/bwestrich/tdd-spock/blob/master/README.md 23
  • 24. © 2015 McW est Corporation Testing Effectively 24
  • 25. © 2015 McW est Corporation Testing effectively • Types of tests • Finding tests • Writing tests • Running tests • Testing before committing 25
  • 26. © 2015 McW est Corporation Types of (automated) tests 26 Type What it tests Spock support Comment Functional how system works from “user’s” perspective Geb Most important Lowest coverage Unit details mocks/stubs Fast, fun Highest coverage Integration how details work together controller web tests* Usage varies for different projects Smoke deployments Geb Spot check * https://github.com/bwestrich/tdd-spock/blob/master/README-MOCKMVC.md
  • 27. © 2015 McW est Corporation Spock uses same syntax for all test types 27
  • 28. © 2015 McW est Corporation Red Green Clean 28 1. Write new or break existing test 2. Fix test 3. Clean (refactor)
  • 29. © 2015 McW est Corporation Don’t trust a test that hasn’t failed -- Kevin Beatty 29
  • 30. © 2015 McW est Corporation Using test types: Unit First 1. Write/break unit test 2. Fix unit test 3. Clean test code and tested code 4. Write/break integration test (optional) 5. Fix integration test 6. Clean test code and tested code 7. Write/break functional test (optional) 8. Fix functional test 9. Clean test code and tested code 30
  • 31. © 2015 McW est Corporation Using test types: Functional First 1. Write/break functional test (optional) 2. Write/break integration test (optional) 3. Write/break unit test 4. Fix unit test 5. Clean test code and tested code 6. Fix integration test 7. Clean test code and tested code 8. Fix functional test 9. Clean test code and tested code 31
  • 32. © 2015 McW est Corporation Order of Test Types for Different Tasks Task Usual Approach Note Defect fix FF Developer-reported defects might use UF New feature (tools and requirements well understood) UF Business requested? FF New feature (when learning technology or requirements) Whatever approach works (even writing code before tests!) Feature is not complete until tests pass and refactoring complete 32 Legend: FF = Functional First, UF = Unit First
  • 33. © 2015 McW est Corporation Write tests as soon as possible • The sooner you write tests, the better they can help guide your design • OK: write code, then (before pushing) test code • Better: write tests while you write the tested code • Best: write tests before the tested code. o Added benefit: verify the test fails before feature written / defect fixed (don’t trust a test that hasn’t failed) 33
  • 34. © 2015 McW est Corporation Different projects use different test types Test type Run duration When run Unit < 1 minute Constantly while coding, pre-push Integration 10 minutes Pre-push Functional None n/a 34 Project: Provide website content for nationwide electronics retailer, no front-end development done by our team.
  • 35. © 2015 McW est Corporation Different projects use different test types Test type Run duration When run Unit < 1 minute Constantly while coding, pre-push Integration 1 minute Occasionally while coding, pre-push Functional 10 minutes Pre-push 35 Project: Departmental app, full-stack development.
  • 36. © 2015 McW est Corporation Reliable integration and functional tests • Don’t tolerate “false positives” • Tests that fail for any reason other than defective software • Decrease value of your tests • “Fix broken windows” • Tips on avoiding “false positives” • @Stepwise • Manage your test data • Extend Geb as needed 36
  • 37. © 2015 McW est Corporation Use @Stepwise to guarantee run method order 37
  • 38. © 2015 McW est Corporation Manage your test data • Script it! • SQL, DBUnit, etc. • Periodically refresh all data in test environments • Reserve ranges for testing • ID numbers (negative IDs? Large IDs?) • Code values • Other special “marking” • Tests should not change shared data (allows concurrent test runs) 38
  • 39. © 2015 McW est Corporation Geb testing of asynchronous JavaScript • Using angular? Try ng-busy to manage asynchronous processing • Use ng-busy to display a ‘Processing’ message to users while waiting for any http server requests, have tests wait when label is displayed Page object method Example code in test 39
  • 40. © 2015 McW est Corporation Using test types: Takeaway • All types of tests are an integral part of development • Use the correct test type for the job at hand • Use test types that fit your project • Write tests as soon as possible • Prevent false-positives • And, of course….. ;-) • Run ALL test types before pushing changes 40
  • 41. © 2015 McW est Corporation Keyboard shortcuts • Learn and use them! (pairing?) • OS and IDE specific • OS: Mac, Linux, Windows • IDE: IntelliJ, Eclipse, nano, emacs, vi, ……. • This presentation uses Mac (OSX) and IntelliJ 14.1.4 41
  • 42. © 2015 McW est Corporation Finding Tests • Test location • As close to Class Under Test as possible • Same project, package, name prefix (MyClass and MyClassSpec) • Different source folder • Keyboard shortcuts (DEMO) • Toggle between class and test: Cmd-Shift-T • Find by name: Cmd-Shift-O o (type caps to exploit camel case, e.g. MCS finds MyClassSpec) 42
  • 43. © 2015 McW est Corporation Writing Tests • Where table keyboard shortcuts (DEMO) • Column editing o Create o Update o Delete • Column formatting: Cmd-Alt-L 43
  • 44. © 2015 McW est Corporation Running Tests (IDE) • Keyboard shortcuts (DEMO) • Ctrl-Shift-R: Run highlighted test • Ctrl-R: Run previously run test 44
  • 45. © 2015 McW est Corporation Running Tests (command line) • Create team aliases for common operations for your team’s languages / frameworks / build systems • Operations o refresh dependencies, clean, test, run • Languages / frameworks: build systems o JavaScript/Angular: grunt, gulp o Java/Groovy/Spring Boot: maven, gradle 45
  • 46. © 2015 McW est Corporation Running tests command line (DEMO) 46
  • 47. © 2015 McW est Corporation Running Tests (command line) (cont.) • Team aliases • Add to source control • Add directory to execution path • Provide easy ways for team to update (“ea”, “listaliases”) • Basic example: https://github.com/mcwest/team-aliases • Supports: 47
  • 48. © 2015 McW est Corporation Test Before Pushing • The right way: Run all tests (of all types) before pushing (to source control) • Why it’s hard to do: • Commands to run tests are arcane, inconsistent, error prone • Tests take long time to run • Tests fail after running long time (waste of time!) • Results hard to find/interpret (just say ‘ok’ or ‘not’) • While waiting, you can’t do ANYTHING else • How to make the right way easy? 48
  • 49. © 2015 McW est Corporation Asynchronous pre-push testing (via script) • Call script something short: e.g. “go” • What script does • Cleans and builds all components in separate workspace • Runs ALL unit/integration/functional tests and code style checkers • Fails fast (slow tests run last) • Runs in background o Spawns separate instance of components with dedicated resources (workspace, ports, data, log files, …) o Audio notification of results (have some fun here!) • Manage same as a team alias (in source control, on execution path) 49
  • 50. © 2015 McW est Corporation Before svn commit 1. ‘go’, then if errors, fix and refactor 2. ‘svn update’ 3. if changes, go back to step 1, otherwise ‘svn commit’ 50
  • 51. © 2015 McW est Corporation Before git push 1. ‘go’, then if errors, fix and refactor 2. ‘git commit’ 3. ‘git smart-pull’ (alias ‘gsp’) 4. if changes, go back to step 1, otherwise ‘git push’ • Notes: • Step #2 makes git merges easier to manage by not mixing local changes and remote changes into same commit • Step #3 uses the excellent git smart-pull add-on, see https://github.com/mcwest/team-aliases for more info 51
  • 52. © 2015 McW est Corporation Asynchronous pre-push testing (other methods) • Team City (JetBrains): not out of the box, need to configure post-commit hook • Other tools? • Anyone have solutions to share to this? 52
  • 53. © 2015 McW est Corporation Testing effectively (review) • Types of tests • Finding tests • Writing tests • Running tests • Testing before committing 53
  • 54. © 2015 McW est Corporation TDD in Teams • Pair Programming • Pull Requests • Continuous Integration • Continuous Deployment 54
  • 55. © 2015 McW est Corporation Pair Programming • Wonderful way to learn, teach, enjoy TDD/Spock • Very productive • Roles • Driver (shows new ways to find/write/run/commit tests) • Observer (watches for typos, testing the right thing, next test type) • Keep both members switching roles • TDD ping pong: ping pong ping pong ping pong • Other ideas? • Cautions • Team must want to pair (pre-interview question) • Workspace must be conducive to pairing 55
  • 56. © 2015 McW est Corporation Pair Programming Workspace 56
  • 57. © 2015 McW est Corporation Pull Requests (PR) • Great compliment to / replacement for pairing • Does not require workspace re-config • Works with remote teams (but can pair over skype/hangouts/…) • More conducive to some developers’ workstyles than pairing • TDD and PRs • Submitter must include tests in the PR • Reviewer should run tests in background (using ‘go’) while reviewing • Cautions • Requires understanding of source code branching • Commands to create PR’s not trivial o Set up command line aliases to streamline 57
  • 58. © 2015 McW est Corporation Continuous Integration • Trigger build immediately on push (commit hooks preferred over polling) • Notify team of broken builds • Emails • Texts • IM/Slack? • Make broken builds visible • Radiator (Jenkins plugin) 58
  • 59. © 2015 McW est Corporation Continuous Deployment • Impossible without automated tests • TDD a great way (the only way) to build automated tests that verify a system at all levels 59
  • 60. © 2015 McW est Corporation Test Mantras Mantra -- “a statement or slogan repeated frequently” • Test the right thing • APIs not internals • Don’t trust a test that hasn’t failed • The right way easy • Tests are assets not afterthoughts 60
  • 61. © 2015 McW est Corporation Spock: Specification at all levels 61
  • 62. © 2015 McW est Corporation From the smallest unit… 62
  • 63. © 2015 McW est Corporation … to detailed interactions … 63
  • 64. © 2015 McW est Corporation … to higher level interactions … 64
  • 65. © 2015 McW est Corporation … to the user’s view of the system. 65
  • 66. © 2015 McW est Corporation The needs of the many outweigh the needs of the few. 66
  • 67. © 2015 McW est Corporation Conclusion Using the techniques and approaches we’ve discussed, automated developer-written tests become less something we do as an afterthought (if at all), and more an asset we demand on our future projects. 67
  • 68. © 2015 McW est Corporation Resources • Spock TDD: https://github.com/bwestrich/tdd-spock • TDD cribsheet (JUnit oriented): https://bitbucket.org/bwestrich/java-tdd • Command line aliases: https://github.com/mcwest/team-aliases 68
  • 69. © 2015 McW est Corporation 69 Spock ‘seed art’ credit
  • 70. © 2015 McW est Corporation Minneapolis ‘seed art’ credit 70
  • 71. © 2015 McW est Corporation Spock TDD Tests as Assets not Afterthoughts by Brian Westrich, McWest Corp. bw@mcwest.com 71