SlideShare a Scribd company logo
Unit Testing,  Test Driven Development  and the Walking Skeleton Seb Rose Twitter:  @sebrose Blog:  claysnow.blogspot.com E-mail: [email_address] Phone: 01721 788178
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
Don’t we all know enough about testing? Lots of software has insufficient automated testing How much manual testing goes on at YOUR workplace? Testing is still seen as a 2 nd  class activity What do YOU drop when you’re under time pressure? Tests are often written after the code Is YOUR code always testable? Plenty see tests as a drag on development Do your tests inhibit changes to YOUR architecture? Not everyone cares about all the tests Does everyone run YOUR tests every check-in? Who cares when YOUR tests break?
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
One book to rule them all? Pulls together current thinking Walking skeleton Acceptance Test Driven Development Test Driven Development Includes OO design philosophy Ports and connectors Small decoupled classes Do not Repeat Yourself Tell, don’t ask Worked example
DISCLAIMER I am not affiliated to Freeman/Pryce I have never worked with them I barely know them The book stands on its own Mailing list: growing-object-oriented-software@googlegroups.com
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
What is a walking skeleton? Automatically buildable Automatically deployable Automatically testable No functionality required Initial architecture
Why start with the skeleton? The infrastructure of build, deploy, test can be time consuming to implement You WILL need it, so do it first If you don’t do it now, WHEN will you have time? The skeleton gives early visibility Without a skeleton it is hard to drive development OUTSIDE-IN Acceptance Test Driven Development (ATDD) is a powerful tool
Acceptance Test Driven Development Document functionality using acceptance tests Tests readable by ‘business people’ FIT / Fitnesse Cucumber Can replace specifications / user stories in some environments. Needs commitment from whole organisation
Red, Green, Refactor
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
What is TDD? Test Driven Development aka Test Driven Design A software development practice Popularised by agile processes (like XP) A development process that generates, among other things, (automated) unit tests TDD is NOT a replacement for system/integration testing.
The basics Write a failing test Write just enough code to make it pass Refactor Repeat
 
When does unit testing become TDD? The test is written BEFORE the code The test is RUN before the code is written The test must FAIL The code is written to SATISFY the test Code is ONLY written to satisfy a test Run all tests The tests must PASS REFACTOR the code & tests to production quality Ensure all tests still pass Remember TDD code must be of PRODUCTION QUALITY
TDD and “agile” Agile Manifesto:  Individuals and interactions over processes and tools Working software over comprehensive documentation Customer collaboration over contract negotiation Responding to change over following a plan  TDD is one of several agile practices “Agile practices are not optional” – Mike Kohn
Emergent design Big Up Front Design impedes delivery of working code, but Initially it’s uncomfortable working without BUFD Planning & partitioning work is harder Architecture still important Walking skeleton – initial application architecture Intentional – deliberate conscious decisions Rework is  inevitable TDD makes refactoring less error prone BUT since tests are of ‘production’ quality this is cheap
Executable Documentation Prefer documenting your design in tests Documentation can often be out of date Comments can often be out of date Tests run with every build, so CANNOT be broken Not an excuse for NO documentation Architecture Vision Scenarios/Use cases/Competencies More confidence in documentation that can be verified automatically  i.e. tests
Challenges At first I found that: Working without detailed designs was uncomfortable Writing tests first was unnatural Ensuring testability was confusing Productivity decreased Over time I noticed that: The tests gave me confidence New habits became familiar Defects and regressions decreased
For TDD to work Tests need to be easy to run All developers and build processes need to run them Tests need to be fast to run Ran every few minutes or seconds Partition test suites to keep fast Build needs to be quick Partition application to keep fast Test failures need to be handled Process Team commitment
Stop Press: “TDD no substitute for testing” TDD relies on  Unit Tests aka Developer Tests Unit Tests: Document the code Can’t become out of date Well structured (like production code) Don’t cover traditional “test team” scenarios Testing is just as important as ever Integration, System, Acceptance etc.
TDD summary TDD is a DEVELOPER activity It delivers: (Automatically) Testable software Higher test coverage Lower defect rates Reliable refactoring TDD is not a replacement for integration or system testing
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
What is Unit Testing? A unit test isolates a part of the program tests a single behaviour clearly identifies any reason for failure documents expected behaviour runs quickly
No free lunch Writing unit tests takes time and skill Refactoring unit tests takes time and skill Running unit tests takes time Interpreting unit test failures takes time and skill Fixing defects takes time and skill Fixing defects early costs less than fixing them late “ Unit Testing is the most cost effective testing activity you can do. Defects removed in Unit Testing cost around 10 times less than defects removed in Functional verification and around 40 times less than defects removed by Systems or Integration testing.”
Testability Testability needs to be designed in TDD ensures code is testable Code with hidden dependencies is hard to test Dependency Injection/Inversion Pass dependencies into code under test Write factories that permit injection of test doubles Interfaces should be cohesive Wide interfaces encourage unnecessary coupling Avoid globals, singletons etc. Retro-fitting unit tests is hard Take small steps Introduce a ‘seam’ – c.f. Working Effectively with Legacy Code
A test is not a unit test if: It talks to the database It communicates across the network It touches the file system It can’t run at the same time as other unit tests You have to do special things to your environment (such as editing config files) to run it (Michael Feathers’ blog, 2005)
Necessity Test observable behaviour Don’t modify encapsulation to aid testing If a behaviour isn’t observable through the public interface what is it for? Don’t slavishly write one test per method Test behaviours Some methods may not need any dedicated tests Methods that implement useful behaviours may need many tests Choose test variants carefully Edge conditions Invalid inputs Multiple invocations Assert invariants Error signalling
Granularity Test a SINGLE observable behaviour It is tempting to combine related behaviours in a single test – DON’T … even if EXACTLY the same steps are needed public void shouldSortTwoStringsAndReportCorrectSize() { SortedSet<String> animals = new TreeSet<String>(); animals.add(“Zebra”); animals.add(“Anteater”); assertEquals(2, animals.size()); assertEquals(“Anteater”, animals.first()); assertEquals(“Zebra”, animals.last()); }
Understandability Test a single observable behaviour (again) Name tests to describe the behaviour under test Describe nature of the test Is it checking that preconditions are enforced? Is a dependency going to signal an error? Long names are fine – you only type them once Be precise shouldReturnCorrectValue is not a good name for a test shouldReturnCorrectSumOfTwoIntegersWithoutOverflow should_return_correct_sum_of_two_integers_without_overflow When a test fails you want to know WHAT WENT WRONG You don’t want to reverse engineer the test You don’t want to run smaller tests to isolate the failure
Maintainability Unit Tests should be written to same quality as Production code Tests will be maintained and read just as often as production code Code is communication to other developers not just a compiler Organise tests into cohesive suites Refactor tests to avoid duplication Use suites to perform common set up/tear down operations Extract common code into methods Extract common functionality into classes Remove redundant tests
Reiteration: 5 -ities Testability Necessity Granularity Understandability Maintainability MUNGT ? TeNGUM?
Tests can only be run once they have been written Resist pressure to add unit tests ‘later’ Untested code should not be committed to codebase How can you know code is testable? There are always more pressing things to do tomorrow “ Legacy code is code without unit tests” – Michael Feathers Keep tests in same changeset as functionality they test Aids traceability and auditing Subject tests to same quality control as production code Apply usual coding standards Buddy check/peer review should examine completeness of tests
Tests are only useful when they are run Run the tests automatically Developer builds should run them while writing code Continuous Integration server builds should run them Release/nightly builds should run them Test failure == build failure At each stage of the process, fail the build if a test is broken Failing tests should automatically fail the build Automatic notification necessary Respond quickly Fixing a failed test is highest priority Responsibility of whole team Resist pressure for “just for now” fix
Demonstrate value of unit tests Unit testing takes time, up front Lots of evidence that it saves time later on Still need to demonstrate that its working in your team Collect metrics now (some suggestions) Coverage - how much code is tested? Defects per feature Regressions per iteration Velocity Collect metrics continuously Integrate collection with your process Publish trends Expect a learning curve
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
A few myths I hope I’ve dispelled “Testing is a job for testers” “Now that we ‘do’ TDD we don’t need any testers” “Tests are only important while the code is being written” “Tests aren’t as important as production code” “What does it matter what I call it? It’s only a test!” “Why should I fix it? It’s not my code!” “We can always add the tests next iteration” “There’s not enough time to write tests”
Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
Questions? Most of the information from this session can also be found in: “ Testing Times” published this month in C Vu, the magazine of ACCU www.accu.org Contact me: [email_address] @sebrose 01721 788178 claysnow.blogspot.com
References Growing Object-Oriented Software Guided by Tests – Freeman/Pryce Bridging the communications gap – Gojko Adzic Fit for developing software – Mugridge/Cunningham Test Driven Development - Kent Beck Working Effectively with Legacy Code – Michael Feathers Succeeding with Agile – Mike Cohn Refactoring: Improving the Design of Existing Code – Martin Fowler Clean code – Robert Martin JUnit Recipes – J.B. Rainsberger xUnit Test Patterns – Gerard Meszaros

More Related Content

What's hot (20)

PDF
An introduction to unit testing
Adam Stephensen
 
PPTX
Test Case Management Tools
Malang QA Community
 
PPTX
Types of performance testing
NaveenKumar Namachivayam
 
PPS
Boundary and equivalnce systematic test design
Ian McDonald
 
PPT
Test Automation Framework Designs
Sauce Labs
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPT
TDD (Test Driven Design)
nedirtv
 
PDF
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
PPT
testng
harithakannan
 
PPTX
An Introduction to Unit Testing
Joe Tremblay
 
PPTX
Automation Framework Presentation
Ben Ngo
 
PDF
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
PDF
Test Automation
nikos batsios
 
PPTX
Unit testing
princezzlove
 
PDF
Test Driven Development (TDD)
David Ehringer
 
PPTX
Test automation framework
QACampus
 
PPTX
API Test Automation Using Karate (Anil Kumar Moka)
Peter Thomas
 
PDF
Unit Testing in Python
Haim Michael
 
PDF
Robot Framework Dos And Don'ts
Pekka Klärck
 
An introduction to unit testing
Adam Stephensen
 
Test Case Management Tools
Malang QA Community
 
Types of performance testing
NaveenKumar Namachivayam
 
Boundary and equivalnce systematic test design
Ian McDonald
 
Test Automation Framework Designs
Sauce Labs
 
Unit Testing Concepts and Best Practices
Derek Smith
 
TDD (Test Driven Design)
nedirtv
 
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
An Introduction to Unit Testing
Joe Tremblay
 
Automation Framework Presentation
Ben Ngo
 
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
Test Automation
nikos batsios
 
Unit testing
princezzlove
 
Test Driven Development (TDD)
David Ehringer
 
Test automation framework
QACampus
 
API Test Automation Using Karate (Anil Kumar Moka)
Peter Thomas
 
Unit Testing in Python
Haim Michael
 
Robot Framework Dos And Don'ts
Pekka Klärck
 

Viewers also liked (20)

PPT
Elevator Pitch Tips
Marc Nathan
 
PDF
Walking Skeleton as presented at ACCU 2015 in Bristol, England
TSundberg
 
PPTX
200808 AIM Walking Skeleton
Troy Young
 
PPTX
Daniil Michailovas - Agile estimating and planning
Agile Lietuva
 
PPTX
Agile planning and estimating
Brett Child
 
PDF
Icinga 2: Einrichten von Notifications (Webinar vom 21. Januar 2016)
NETWAYS
 
PDF
User Story Mapping
Luis Antonio Salazar Caraballo
 
PDF
Agile Estimating & Planning by Amaad Qureshi
Amaad Qureshi
 
PPTX
full-stack agile: Common Agile Myths
Ashley-Christian Hardy
 
PPTX
Easy Talk 4 Teens - Advanced : Elevator Speech
Rebecca Reed
 
PPTX
30 Sec Pitch - for High School Students
Rick Stomphorst
 
PPTX
Architecture In An Agile World
James Cooper
 
PPT
Walking Skeleton
hepphep
 
PPTX
User Story Mapping Workshop
Dana Pylayeva
 
PPT
Short scrum games the efficient way to produce team cohesion
Agileee
 
PPTX
full-stack agile - Scrum Basics
Ashley-Christian Hardy
 
PDF
Story Mapping in a Nutshell
VersionOne
 
PDF
Agile Requirements with User Story Mapping
Andreas Hägglund
 
PDF
User Story Mapping Workshop (Design Skills 2016)
Bartosz Mozyrko
 
PDF
Agile at Spotify
Joakim Sundén
 
Elevator Pitch Tips
Marc Nathan
 
Walking Skeleton as presented at ACCU 2015 in Bristol, England
TSundberg
 
200808 AIM Walking Skeleton
Troy Young
 
Daniil Michailovas - Agile estimating and planning
Agile Lietuva
 
Agile planning and estimating
Brett Child
 
Icinga 2: Einrichten von Notifications (Webinar vom 21. Januar 2016)
NETWAYS
 
User Story Mapping
Luis Antonio Salazar Caraballo
 
Agile Estimating & Planning by Amaad Qureshi
Amaad Qureshi
 
full-stack agile: Common Agile Myths
Ashley-Christian Hardy
 
Easy Talk 4 Teens - Advanced : Elevator Speech
Rebecca Reed
 
30 Sec Pitch - for High School Students
Rick Stomphorst
 
Architecture In An Agile World
James Cooper
 
Walking Skeleton
hepphep
 
User Story Mapping Workshop
Dana Pylayeva
 
Short scrum games the efficient way to produce team cohesion
Agileee
 
full-stack agile - Scrum Basics
Ashley-Christian Hardy
 
Story Mapping in a Nutshell
VersionOne
 
Agile Requirements with User Story Mapping
Andreas Hägglund
 
User Story Mapping Workshop (Design Skills 2016)
Bartosz Mozyrko
 
Agile at Spotify
Joakim Sundén
 
Ad

Similar to Unit Testing, TDD and the Walking Skeleton (20)

PPT
Test-Driven Development
adrianmitev
 
PPTX
Test Driven Development
Md. Enamul Haque Chowdhury
 
PDF
Tdd
Dmitry Savin
 
PDF
Driven to Tests
Kevlin Henney
 
PDF
Test-Driven Development Reference Card
Seapine Software
 
PDF
An Introduction to Test Driven Development
CodeOps Technologies LLP
 
PDF
Beyond Testing: Specs and Behavior Driven Development
Rabble .
 
PPTX
Unit Testing and TDD 2017
Xavi Hidalgo
 
PDF
Test Driven Development
Hicham El Hammouchi
 
PDF
Writing Tests Effectively
Paul Boocock
 
PPT
Automated Unit Testing and TDD
Greg Sohl
 
PPTX
TDD in Agile
Atish Narlawar
 
PPTX
Test driven development
namkha87
 
PPTX
Test-Driven Development
Meilan Ou
 
PPTX
Test-Driven Development In Action
Jon Kruger
 
PPTX
Test driven development
Sunil Prasad
 
PPT
Introduction to Test Driven Development
Michael Denomy
 
PPTX
TeDevelopment Testing in Software Engineering
Karthik Rohan
 
PPTX
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Test-Driven Development
adrianmitev
 
Test Driven Development
Md. Enamul Haque Chowdhury
 
Driven to Tests
Kevlin Henney
 
Test-Driven Development Reference Card
Seapine Software
 
An Introduction to Test Driven Development
CodeOps Technologies LLP
 
Beyond Testing: Specs and Behavior Driven Development
Rabble .
 
Unit Testing and TDD 2017
Xavi Hidalgo
 
Test Driven Development
Hicham El Hammouchi
 
Writing Tests Effectively
Paul Boocock
 
Automated Unit Testing and TDD
Greg Sohl
 
TDD in Agile
Atish Narlawar
 
Test driven development
namkha87
 
Test-Driven Development
Meilan Ou
 
Test-Driven Development In Action
Jon Kruger
 
Test driven development
Sunil Prasad
 
Introduction to Test Driven Development
Michael Denomy
 
TeDevelopment Testing in Software Engineering
Karthik Rohan
 
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Ad

More from Seb Rose (20)

PDF
AI and developer obsolescence - BCS 2025.pdf
Seb Rose
 
PDF
Software contracts - Global Enterprise Agile 2023.pdf
Seb Rose
 
PDF
Micro-service delivery - without the pitfalls
Seb Rose
 
PDF
DevSecOps - Agile Get-Together 2022.pdf
Seb Rose
 
PDF
Contract testing - Sealights 2022.pdf
Seb Rose
 
PDF
Example mapping - slice any story into testable examples - SoCraTes 2022.pdf
Seb Rose
 
PDF
Software testing - learning to walk again (expoQA22)
Seb Rose
 
PDF
DevSecOps - Unicom Agile and DevOps Expo (Adaptive Challenges) 2021
Seb Rose
 
PDF
A brief history of requirements - Unicom 2022
Seb Rose
 
PDF
Example mapping (with builds) - ProductWorld 2022
Seb Rose
 
PDF
Example mapping - ProductWorld 2022
Seb Rose
 
PDF
No code, low code, machine code QA ATL 2021
Seb Rose
 
PDF
No code, low code, machine code QA ATL 2021
Seb Rose
 
PDF
No code, low code, machine code - Unicom 2021
Seb Rose
 
PDF
BDD: from soup to nuts - The Future of Work Scotland 2021
Seb Rose
 
PDF
Contrasting test automation and BDD - 2020
Seb Rose
 
PDF
Are BDD and test automation the same thing? Automation Guild 2021
Seb Rose
 
PDF
"Our BDDs are broken!" Lean Agile Exchange 2020
Seb Rose
 
PDF
User stories: from good intentions to bad advice - Agile Scotland 2019
Seb Rose
 
PDF
User stories: from good intentions to bad advice - Lean Agile Scotland 2019
Seb Rose
 
AI and developer obsolescence - BCS 2025.pdf
Seb Rose
 
Software contracts - Global Enterprise Agile 2023.pdf
Seb Rose
 
Micro-service delivery - without the pitfalls
Seb Rose
 
DevSecOps - Agile Get-Together 2022.pdf
Seb Rose
 
Contract testing - Sealights 2022.pdf
Seb Rose
 
Example mapping - slice any story into testable examples - SoCraTes 2022.pdf
Seb Rose
 
Software testing - learning to walk again (expoQA22)
Seb Rose
 
DevSecOps - Unicom Agile and DevOps Expo (Adaptive Challenges) 2021
Seb Rose
 
A brief history of requirements - Unicom 2022
Seb Rose
 
Example mapping (with builds) - ProductWorld 2022
Seb Rose
 
Example mapping - ProductWorld 2022
Seb Rose
 
No code, low code, machine code QA ATL 2021
Seb Rose
 
No code, low code, machine code QA ATL 2021
Seb Rose
 
No code, low code, machine code - Unicom 2021
Seb Rose
 
BDD: from soup to nuts - The Future of Work Scotland 2021
Seb Rose
 
Contrasting test automation and BDD - 2020
Seb Rose
 
Are BDD and test automation the same thing? Automation Guild 2021
Seb Rose
 
"Our BDDs are broken!" Lean Agile Exchange 2020
Seb Rose
 
User stories: from good intentions to bad advice - Agile Scotland 2019
Seb Rose
 
User stories: from good intentions to bad advice - Lean Agile Scotland 2019
Seb Rose
 

Recently uploaded (20)

PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
July Patch Tuesday
Ivanti
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
July Patch Tuesday
Ivanti
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

Unit Testing, TDD and the Walking Skeleton

  • 1. Unit Testing, Test Driven Development and the Walking Skeleton Seb Rose Twitter: @sebrose Blog: claysnow.blogspot.com E-mail: [email_address] Phone: 01721 788178
  • 2. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 3. Don’t we all know enough about testing? Lots of software has insufficient automated testing How much manual testing goes on at YOUR workplace? Testing is still seen as a 2 nd class activity What do YOU drop when you’re under time pressure? Tests are often written after the code Is YOUR code always testable? Plenty see tests as a drag on development Do your tests inhibit changes to YOUR architecture? Not everyone cares about all the tests Does everyone run YOUR tests every check-in? Who cares when YOUR tests break?
  • 4. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 5. One book to rule them all? Pulls together current thinking Walking skeleton Acceptance Test Driven Development Test Driven Development Includes OO design philosophy Ports and connectors Small decoupled classes Do not Repeat Yourself Tell, don’t ask Worked example
  • 6. DISCLAIMER I am not affiliated to Freeman/Pryce I have never worked with them I barely know them The book stands on its own Mailing list: [email protected]
  • 7. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 8. What is a walking skeleton? Automatically buildable Automatically deployable Automatically testable No functionality required Initial architecture
  • 9. Why start with the skeleton? The infrastructure of build, deploy, test can be time consuming to implement You WILL need it, so do it first If you don’t do it now, WHEN will you have time? The skeleton gives early visibility Without a skeleton it is hard to drive development OUTSIDE-IN Acceptance Test Driven Development (ATDD) is a powerful tool
  • 10. Acceptance Test Driven Development Document functionality using acceptance tests Tests readable by ‘business people’ FIT / Fitnesse Cucumber Can replace specifications / user stories in some environments. Needs commitment from whole organisation
  • 12. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 13. What is TDD? Test Driven Development aka Test Driven Design A software development practice Popularised by agile processes (like XP) A development process that generates, among other things, (automated) unit tests TDD is NOT a replacement for system/integration testing.
  • 14. The basics Write a failing test Write just enough code to make it pass Refactor Repeat
  • 15.  
  • 16. When does unit testing become TDD? The test is written BEFORE the code The test is RUN before the code is written The test must FAIL The code is written to SATISFY the test Code is ONLY written to satisfy a test Run all tests The tests must PASS REFACTOR the code & tests to production quality Ensure all tests still pass Remember TDD code must be of PRODUCTION QUALITY
  • 17. TDD and “agile” Agile Manifesto: Individuals and interactions over processes and tools Working software over comprehensive documentation Customer collaboration over contract negotiation Responding to change over following a plan TDD is one of several agile practices “Agile practices are not optional” – Mike Kohn
  • 18. Emergent design Big Up Front Design impedes delivery of working code, but Initially it’s uncomfortable working without BUFD Planning & partitioning work is harder Architecture still important Walking skeleton – initial application architecture Intentional – deliberate conscious decisions Rework is inevitable TDD makes refactoring less error prone BUT since tests are of ‘production’ quality this is cheap
  • 19. Executable Documentation Prefer documenting your design in tests Documentation can often be out of date Comments can often be out of date Tests run with every build, so CANNOT be broken Not an excuse for NO documentation Architecture Vision Scenarios/Use cases/Competencies More confidence in documentation that can be verified automatically i.e. tests
  • 20. Challenges At first I found that: Working without detailed designs was uncomfortable Writing tests first was unnatural Ensuring testability was confusing Productivity decreased Over time I noticed that: The tests gave me confidence New habits became familiar Defects and regressions decreased
  • 21. For TDD to work Tests need to be easy to run All developers and build processes need to run them Tests need to be fast to run Ran every few minutes or seconds Partition test suites to keep fast Build needs to be quick Partition application to keep fast Test failures need to be handled Process Team commitment
  • 22. Stop Press: “TDD no substitute for testing” TDD relies on Unit Tests aka Developer Tests Unit Tests: Document the code Can’t become out of date Well structured (like production code) Don’t cover traditional “test team” scenarios Testing is just as important as ever Integration, System, Acceptance etc.
  • 23. TDD summary TDD is a DEVELOPER activity It delivers: (Automatically) Testable software Higher test coverage Lower defect rates Reliable refactoring TDD is not a replacement for integration or system testing
  • 24. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 25. What is Unit Testing? A unit test isolates a part of the program tests a single behaviour clearly identifies any reason for failure documents expected behaviour runs quickly
  • 26. No free lunch Writing unit tests takes time and skill Refactoring unit tests takes time and skill Running unit tests takes time Interpreting unit test failures takes time and skill Fixing defects takes time and skill Fixing defects early costs less than fixing them late “ Unit Testing is the most cost effective testing activity you can do. Defects removed in Unit Testing cost around 10 times less than defects removed in Functional verification and around 40 times less than defects removed by Systems or Integration testing.”
  • 27. Testability Testability needs to be designed in TDD ensures code is testable Code with hidden dependencies is hard to test Dependency Injection/Inversion Pass dependencies into code under test Write factories that permit injection of test doubles Interfaces should be cohesive Wide interfaces encourage unnecessary coupling Avoid globals, singletons etc. Retro-fitting unit tests is hard Take small steps Introduce a ‘seam’ – c.f. Working Effectively with Legacy Code
  • 28. A test is not a unit test if: It talks to the database It communicates across the network It touches the file system It can’t run at the same time as other unit tests You have to do special things to your environment (such as editing config files) to run it (Michael Feathers’ blog, 2005)
  • 29. Necessity Test observable behaviour Don’t modify encapsulation to aid testing If a behaviour isn’t observable through the public interface what is it for? Don’t slavishly write one test per method Test behaviours Some methods may not need any dedicated tests Methods that implement useful behaviours may need many tests Choose test variants carefully Edge conditions Invalid inputs Multiple invocations Assert invariants Error signalling
  • 30. Granularity Test a SINGLE observable behaviour It is tempting to combine related behaviours in a single test – DON’T … even if EXACTLY the same steps are needed public void shouldSortTwoStringsAndReportCorrectSize() { SortedSet<String> animals = new TreeSet<String>(); animals.add(“Zebra”); animals.add(“Anteater”); assertEquals(2, animals.size()); assertEquals(“Anteater”, animals.first()); assertEquals(“Zebra”, animals.last()); }
  • 31. Understandability Test a single observable behaviour (again) Name tests to describe the behaviour under test Describe nature of the test Is it checking that preconditions are enforced? Is a dependency going to signal an error? Long names are fine – you only type them once Be precise shouldReturnCorrectValue is not a good name for a test shouldReturnCorrectSumOfTwoIntegersWithoutOverflow should_return_correct_sum_of_two_integers_without_overflow When a test fails you want to know WHAT WENT WRONG You don’t want to reverse engineer the test You don’t want to run smaller tests to isolate the failure
  • 32. Maintainability Unit Tests should be written to same quality as Production code Tests will be maintained and read just as often as production code Code is communication to other developers not just a compiler Organise tests into cohesive suites Refactor tests to avoid duplication Use suites to perform common set up/tear down operations Extract common code into methods Extract common functionality into classes Remove redundant tests
  • 33. Reiteration: 5 -ities Testability Necessity Granularity Understandability Maintainability MUNGT ? TeNGUM?
  • 34. Tests can only be run once they have been written Resist pressure to add unit tests ‘later’ Untested code should not be committed to codebase How can you know code is testable? There are always more pressing things to do tomorrow “ Legacy code is code without unit tests” – Michael Feathers Keep tests in same changeset as functionality they test Aids traceability and auditing Subject tests to same quality control as production code Apply usual coding standards Buddy check/peer review should examine completeness of tests
  • 35. Tests are only useful when they are run Run the tests automatically Developer builds should run them while writing code Continuous Integration server builds should run them Release/nightly builds should run them Test failure == build failure At each stage of the process, fail the build if a test is broken Failing tests should automatically fail the build Automatic notification necessary Respond quickly Fixing a failed test is highest priority Responsibility of whole team Resist pressure for “just for now” fix
  • 36. Demonstrate value of unit tests Unit testing takes time, up front Lots of evidence that it saves time later on Still need to demonstrate that its working in your team Collect metrics now (some suggestions) Coverage - how much code is tested? Defects per feature Regressions per iteration Velocity Collect metrics continuously Integrate collection with your process Publish trends Expect a learning curve
  • 37. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 38. A few myths I hope I’ve dispelled “Testing is a job for testers” “Now that we ‘do’ TDD we don’t need any testers” “Tests are only important while the code is being written” “Tests aren’t as important as production code” “What does it matter what I call it? It’s only a test!” “Why should I fix it? It’s not my code!” “We can always add the tests next iteration” “There’s not enough time to write tests”
  • 39. Agenda Introduction GOOS Walking Skeleton Test Driven Development Unit Testing Myths Wrap up
  • 40. Questions? Most of the information from this session can also be found in: “ Testing Times” published this month in C Vu, the magazine of ACCU www.accu.org Contact me: [email_address] @sebrose 01721 788178 claysnow.blogspot.com
  • 41. References Growing Object-Oriented Software Guided by Tests – Freeman/Pryce Bridging the communications gap – Gojko Adzic Fit for developing software – Mugridge/Cunningham Test Driven Development - Kent Beck Working Effectively with Legacy Code – Michael Feathers Succeeding with Agile – Mike Cohn Refactoring: Improving the Design of Existing Code – Martin Fowler Clean code – Robert Martin JUnit Recipes – J.B. Rainsberger xUnit Test Patterns – Gerard Meszaros

Editor's Notes

  • #26: “ Run quickly” not covered specifically in this deck. Avoiding dependency on external systems will generally permit tests to run fast. Some computationally intensive tests may be slow – consider moving these out of unit test suite. Becomes a serious issue when practicing TDD