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

PPTX
Риски в тестировании
PDF
Cypress - Best Practices
PDF
Introduction cypress
PPT
Agile Testing Process
PPTX
Introduction to Integration Testing With Cypress
PDF
Automated testing with Cypress
PPTX
Cypress for Testing
PDF
Verification and validation
Риски в тестировании
Cypress - Best Practices
Introduction cypress
Agile Testing Process
Introduction to Integration Testing With Cypress
Automated testing with Cypress
Cypress for Testing
Verification and validation

What's hot (20)

PDF
ソフトウェアテストことはじめ
PPT
Manual testing concepts course 1
PPTX
Introduction to performance testing
PPTX
QA Best Practices in Agile World_new
PDF
Automation testing introduction for FujiNet
PPTX
STLC-ppt-1.pptx
PPTX
Agile Testing and Test Automation
PPT
Testing and Mocking Object - The Art of Mocking.
ODP
Présentation Agile Testing
PPT
Stratégie de tests type
PPTX
Test Driven Development (TDD) Preso 360|Flex 2010
PPTX
Defect life cycle and Defect Status Life Cycle
PPTX
Best Practices for Test Case Writing
PPT
QACampus PPT (STLC)
PDF
발표자료 1인qa로살아남는6가지방법
PPTX
Cypress Testing.pptx
PPT
Scrum Testing Methodology
PPTX
Load testing jmeter
PDF
TDD Flow: The Mantra in Action
ソフトウェアテストことはじめ
Manual testing concepts course 1
Introduction to performance testing
QA Best Practices in Agile World_new
Automation testing introduction for FujiNet
STLC-ppt-1.pptx
Agile Testing and Test Automation
Testing and Mocking Object - The Art of Mocking.
Présentation Agile Testing
Stratégie de tests type
Test Driven Development (TDD) Preso 360|Flex 2010
Defect life cycle and Defect Status Life Cycle
Best Practices for Test Case Writing
QACampus PPT (STLC)
발표자료 1인qa로살아남는6가지방법
Cypress Testing.pptx
Scrum Testing Methodology
Load testing jmeter
TDD Flow: The Mantra in Action
Ad

Viewers also liked (20)

PPT
Elevator Pitch Tips
PDF
Walking Skeleton as presented at ACCU 2015 in Bristol, England
PPTX
200808 AIM Walking Skeleton
PPTX
Daniil Michailovas - Agile estimating and planning
PPTX
Agile planning and estimating
PDF
Icinga 2: Einrichten von Notifications (Webinar vom 21. Januar 2016)
PDF
User Story Mapping
PDF
Agile Estimating & Planning by Amaad Qureshi
PPTX
full-stack agile: Common Agile Myths
PPTX
Easy Talk 4 Teens - Advanced : Elevator Speech
PPTX
30 Sec Pitch - for High School Students
PPTX
Architecture In An Agile World
PPT
Walking Skeleton
PPTX
User Story Mapping Workshop
PPT
Short scrum games the efficient way to produce team cohesion
PPTX
full-stack agile - Scrum Basics
PDF
Story Mapping in a Nutshell
PDF
Agile Requirements with User Story Mapping
PDF
User Story Mapping Workshop (Design Skills 2016)
PDF
Agile at Spotify
Elevator Pitch Tips
Walking Skeleton as presented at ACCU 2015 in Bristol, England
200808 AIM Walking Skeleton
Daniil Michailovas - Agile estimating and planning
Agile planning and estimating
Icinga 2: Einrichten von Notifications (Webinar vom 21. Januar 2016)
User Story Mapping
Agile Estimating & Planning by Amaad Qureshi
full-stack agile: Common Agile Myths
Easy Talk 4 Teens - Advanced : Elevator Speech
30 Sec Pitch - for High School Students
Architecture In An Agile World
Walking Skeleton
User Story Mapping Workshop
Short scrum games the efficient way to produce team cohesion
full-stack agile - Scrum Basics
Story Mapping in a Nutshell
Agile Requirements with User Story Mapping
User Story Mapping Workshop (Design Skills 2016)
Agile at Spotify
Ad

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

PPT
Test-Driven Development
PDF
Test Driven Development (TDD)
PPTX
Test Driven Development
PDF
PDF
Driven to Tests
PDF
Test-Driven Development Reference Card
PDF
An Introduction to Test Driven Development
PDF
Beyond Testing: Specs and Behavior Driven Development
PPTX
Unit Testing and TDD 2017
PDF
Test Driven Development
PDF
Writing Tests Effectively
PPT
Automated Unit Testing and TDD
PPTX
TDD in Agile
PPTX
Test driven development
PPTX
Test-Driven Development
PPTX
Test-Driven Development In Action
PPTX
Test driven development
PPT
Introduction to Test Driven Development
PPTX
TeDevelopment Testing in Software Engineering
Test-Driven Development
Test Driven Development (TDD)
Test Driven Development
Driven to Tests
Test-Driven Development Reference Card
An Introduction to Test Driven Development
Beyond Testing: Specs and Behavior Driven Development
Unit Testing and TDD 2017
Test Driven Development
Writing Tests Effectively
Automated Unit Testing and TDD
TDD in Agile
Test driven development
Test-Driven Development
Test-Driven Development In Action
Test driven development
Introduction to Test Driven Development
TeDevelopment Testing in Software Engineering

More from Seb Rose (20)

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

Recently uploaded (20)

PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Encapsulation theory and applications.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Getting Started with Data Integration: FME Form 101
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Mushroom cultivation and it's methods.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Univ-Connecticut-ChatGPT-Presentaion.pdf
A comparative study of natural language inference in Swahili using monolingua...
OMC Textile Division Presentation 2021.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
Spectral efficient network and resource selection model in 5G networks
Assigned Numbers - 2025 - Bluetooth® Document
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Digital-Transformation-Roadmap-for-Companies.pptx
A comparative analysis of optical character recognition models for extracting...
Encapsulation theory and applications.pdf
Group 1 Presentation -Planning and Decision Making .pptx
NewMind AI Weekly Chronicles - August'25-Week II
Getting Started with Data Integration: FME Form 101
Diabetes mellitus diagnosis method based random forest with bat algorithm
Reach Out and Touch Someone: Haptics and Empathic Computing
Mushroom cultivation and it's methods.pdf
MIND Revenue Release Quarter 2 2025 Press Release
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

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