SlideShare a Scribd company logo
1 of 73
Shaun Abram
Unit Testing
The hard parts
October 10th, 2015
Shaun Abram 2
Test Obsessed?
How much do you know…
Test coverage
Dependency Injection
Mock vs stubs
Testing private or static methods
Test driven development
Shaun Abram 3
What is a unit test?
A piece of code that executes a specific
functionality (‘unit’) in the code, and
Confirms behavior or result is as expected
Determines if code is ‘fit for use’
Does it do what the developer intended?
Before, we manually verified, but not easily
repeatable.
Shaun Abram 4
Why unit test?
Economics $
but also…
Drive design
Create defensive code against bad input
Act as safety buffers for regression bugs
Provide documentation
Clean code
Less bugs
Shaun Abram 5
What is a unit?
 A class? A method? A single path through a method?
 The smallest testable part of an application.
 A single functional use case.
Shaun Abram 6
What makes a good unit test?
Provides benefit!
Readable, Understandable, Maintainable
Independent
run in any order, no DB or File access
Consistent / deterministic
Runs fast
Tests a single logical concept in the system
Shaun Abram 7
Unit testing limitations
 Can not prove the absence of bugs
 Lot’s of code (x3-5)
 Some things difficult to test
Shaun Abram 8
Dependency Injection
9
10
Dependency Injection
 Useful for testing – inject test doubles
 Also helps reduce coupling
Shaun Abram 11
Test Doubles
Mocks
Stubs
Dummies
Spies
Fakes
Shaun Abram 12
Test Doubles
Mocks
Stubs
Dummies
Spies
Fakes
Shaun Abram 13
Test Doubles: Mocks
Mocks: An overloaded term!
uses behavior verification
objects pre-programmed with expectations
14
15
 Mocks use behavior verification
 Can specify how to respond when called
 Roll your own?
Shaun Abram 16
Test Doubles
Mocks
Stubs
Dummies
Spies
Fakes
Shaun Abram 17
Test Doubles: Stubs
‘stubs out’
or provides a simplified version
of the implementation
for the purposes of testing
18
19
 Stubs can use state or behavior verification
 Provides a useful approach for test fixture configurability
Shaun Abram 20
Test Doubles
Mocks
Stubs
Dummies
Spies
Fakes
Shaun Abram 21
Test Doubles: Dummies
A very dumb class!
Contains next to nothing - enough to
compile
Pass when you don’t expect to be used
22
 Use dummies with state or behavior verification
 Can create as inner class
 Can replicate with mocks
Shaun Abram 23
Unit Testing – the tricky parts
Legacy code
Privates
Statics
Shaun Abram 24
General approach to testing legacy code
1) Start with coarse grained tests
No modifications
Strict and rigid
Detect regressions
Short term bridges - delete
Shaun Abram 25
General approach to testing legacy code
1) Start with coarse grained tests
2) Add finer grained tests
Incrementally add more unit
start gently refactoring
Use TDD – if possible
Test from 1) should protect you
Shaun Abram 26
General approach to testing legacy code
1) Start with coarse grained tests
2) Add finer grained tests
3) Continuously refactor
Use patterns such as
Extract Method/Class
Move Method/Field
tease apart methods (>10 lines smells)
Shaun Abram 27
Unit Testing – the tricky parts
Legacy code
Privates
Statics
Shaun Abram 28
How do you test private methods?
Indirectly! Best tested via public interface
But sometimes…
Legacy code
With limited capability to refactor, or
adding a safety net before refactoring
A public method calls several private
methods, each with complex logic
Shaun Abram 29
Testing Private Methods
1. Refactor
2. Change the visibility
Bad practice
Public API? Very bad practice!
Internal & stepping stone -> lesser evil
Java private -> package; .Net protected or
internal?
Document (@VisibleForTesting)
Shaun Abram 30
Testing Private Methods
1. Refactor
2. Change the visibility
3. Use Reflection
No code modification, but…
4. Other options…
Testing frameworks
InternalsVisibleToAttribute
Private Accessors
Shaun Abram 31
Testing static methods
32
33
34
Shaun Abram 35
Testing static methods
DI ideal
But sometimes not pragmatic
36
37
Refactor to wrap the static call in an instance method
Which can then be mocked…
38
39
40
Shaun Abram 41
Testing static methods
Refactor – use DI
Wrap static call in a instance method
Use a mocking framework?
Shaun Abram 42
Test Driven Development
Shaun Abram 43
Test Driven Development
Shaun Abram 44
Test Driven Development
Shaun Abram 45
Test Driven Development
Shaun Abram 46
Test Driven Development
Shaun Abram 47
Test Driven Development
Red - Green – Refactor: the TDD Mantra
No new functionality without a failing test
No refactoring without passing tests
Shaun Abram 48
Test Driven Development Example…
Shaun Abram 49
Test Driven Development Example…
Create a StringCalculator class
with an add method
which takes a comma separate String of numbers
and returns their sum.
Example input Result
0
1 1
2 2
1,2 3
1,2,100 103
Refactor?
Refactor?
These tests act like the original
developer looking over your
shoulder and advising you, long
after that developer has left…
These tests act like the original
developer looking over your
shoulder and advising you, long
after that developer has left…
Shaun Abram 71
Recommended reading
Growing Object-Oriented
Software, Guided by Tests
Freeman & Pryce
Test Driven Development
Kent Beck
Refactoring: Improving the Design
of Existing Code
Martin Fowler, Kent Beck et. al.
Effective Unit Testing
Lasse Koskela
Shaun Abram 72
Recommended reading
Unit Test Best Practices -
https://wiki.tlcinternal.com/display/TD/Unit+Test+Best+Practices
Mocks Arent Stubs -
http://www.martinfowler.com/articles/mocksArentStubs.html
Unit testing - the hard parts

More Related Content

What's hot

World History Ch. 13 Section 4 Notes
World History Ch. 13 Section 4 NotesWorld History Ch. 13 Section 4 Notes
World History Ch. 13 Section 4 Notesskorbar7
 
Revolutions of 1830& 1848 review
Revolutions of 1830& 1848 reviewRevolutions of 1830& 1848 review
Revolutions of 1830& 1848 revieweben_cooke
 
Kristallnacht
KristallnachtKristallnacht
Kristallnachtquillinn
 
Reasons the Nazis gained power - Treaty of versailles
Reasons the Nazis gained power - Treaty of versaillesReasons the Nazis gained power - Treaty of versailles
Reasons the Nazis gained power - Treaty of versaillesmrmarr
 
Hitler and the rise of the nazi party
Hitler and the rise of the nazi partyHitler and the rise of the nazi party
Hitler and the rise of the nazi partyjizbicki
 
World History Ch. 4 Section 1 Notes
World History Ch. 4 Section 1 NotesWorld History Ch. 4 Section 1 Notes
World History Ch. 4 Section 1 Notesskorbar7
 

What's hot (9)

World History Ch. 13 Section 4 Notes
World History Ch. 13 Section 4 NotesWorld History Ch. 13 Section 4 Notes
World History Ch. 13 Section 4 Notes
 
Revolutions of 1830& 1848 review
Revolutions of 1830& 1848 reviewRevolutions of 1830& 1848 review
Revolutions of 1830& 1848 review
 
Kristallnacht
KristallnachtKristallnacht
Kristallnacht
 
The Cold War
The Cold WarThe Cold War
The Cold War
 
27.4 british imperialism in india
27.4 british imperialism in india27.4 british imperialism in india
27.4 british imperialism in india
 
Reasons the Nazis gained power - Treaty of versailles
Reasons the Nazis gained power - Treaty of versaillesReasons the Nazis gained power - Treaty of versailles
Reasons the Nazis gained power - Treaty of versailles
 
Hitler and the rise of the nazi party
Hitler and the rise of the nazi partyHitler and the rise of the nazi party
Hitler and the rise of the nazi party
 
World History Ch. 4 Section 1 Notes
World History Ch. 4 Section 1 NotesWorld History Ch. 4 Section 1 Notes
World History Ch. 4 Section 1 Notes
 
Teacher Notes MODULE 18.pptx
Teacher Notes MODULE 18.pptxTeacher Notes MODULE 18.pptx
Teacher Notes MODULE 18.pptx
 

Viewers also liked

Rest and Microservices at the Las Vegas Dot Net Group
Rest and Microservices at the Las Vegas Dot Net GroupRest and Microservices at the Las Vegas Dot Net Group
Rest and Microservices at the Las Vegas Dot Net GroupShaun Abram
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testingmarkstory
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Triumph Over Legacy Code with Unit Testing
Triumph Over Legacy Code with Unit Testing Triumph Over Legacy Code with Unit Testing
Triumph Over Legacy Code with Unit Testing Typemock
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeTerry Yin
 
RESTful Microservices
RESTful MicroservicesRESTful Microservices
RESTful MicroservicesShaun Abram
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (18)

Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Rest and Microservices at the Las Vegas Dot Net Group
Rest and Microservices at the Las Vegas Dot Net GroupRest and Microservices at the Las Vegas Dot Net Group
Rest and Microservices at the Las Vegas Dot Net Group
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testing
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Triumph Over Legacy Code with Unit Testing
Triumph Over Legacy Code with Unit Testing Triumph Over Legacy Code with Unit Testing
Triumph Over Legacy Code with Unit Testing
 
Automation and Technical Debt
Automation and Technical DebtAutomation and Technical Debt
Automation and Technical Debt
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy Code
 
RESTful Microservices
RESTful MicroservicesRESTful Microservices
RESTful Microservices
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Ship it boise
Ship it boiseShip it boise
Ship it boise
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Unit testing - the hard parts

Working with Legacy Code
Working with Legacy CodeWorking with Legacy Code
Working with Legacy CodeEyal Golan
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentHendrik Neumann
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easierChristian Hujer
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingSahar Nofal
 
Anatomy of Test Driven Development
Anatomy of Test Driven DevelopmentAnatomy of Test Driven Development
Anatomy of Test Driven DevelopmentDhaval Shah
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Test Drive Development
Test Drive DevelopmentTest Drive Development
Test Drive Developmentsatya sudheer
 
Automock: Interaction-Based Mock Code Generation
Automock: Interaction-Based Mock Code GenerationAutomock: Interaction-Based Mock Code Generation
Automock: Interaction-Based Mock Code GenerationSabrina Souto
 

Similar to Unit testing - the hard parts (20)

Effective unit testing
Effective unit testingEffective unit testing
Effective unit testing
 
Working with Legacy Code
Working with Legacy CodeWorking with Legacy Code
Working with Legacy Code
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Continuous Testing
Continuous TestingContinuous Testing
Continuous Testing
 
Anatomy of Test Driven Development
Anatomy of Test Driven DevelopmentAnatomy of Test Driven Development
Anatomy of Test Driven Development
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
Testing
TestingTesting
Testing
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Test Automation
Test AutomationTest Automation
Test Automation
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Drive Development
Test Drive DevelopmentTest Drive Development
Test Drive Development
 
Automock: Interaction-Based Mock Code Generation
Automock: Interaction-Based Mock Code GenerationAutomock: Interaction-Based Mock Code Generation
Automock: Interaction-Based Mock Code Generation
 

Recently uploaded

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 

Recently uploaded (20)

Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 

Unit testing - the hard parts

  • 1. Shaun Abram Unit Testing The hard parts October 10th, 2015
  • 2. Shaun Abram 2 Test Obsessed? How much do you know… Test coverage Dependency Injection Mock vs stubs Testing private or static methods Test driven development
  • 3. Shaun Abram 3 What is a unit test? A piece of code that executes a specific functionality (‘unit’) in the code, and Confirms behavior or result is as expected Determines if code is ‘fit for use’ Does it do what the developer intended? Before, we manually verified, but not easily repeatable.
  • 4. Shaun Abram 4 Why unit test? Economics $ but also… Drive design Create defensive code against bad input Act as safety buffers for regression bugs Provide documentation Clean code Less bugs
  • 5. Shaun Abram 5 What is a unit?  A class? A method? A single path through a method?  The smallest testable part of an application.  A single functional use case.
  • 6. Shaun Abram 6 What makes a good unit test? Provides benefit! Readable, Understandable, Maintainable Independent run in any order, no DB or File access Consistent / deterministic Runs fast Tests a single logical concept in the system
  • 7. Shaun Abram 7 Unit testing limitations  Can not prove the absence of bugs  Lot’s of code (x3-5)  Some things difficult to test
  • 9. 9
  • 10. 10 Dependency Injection  Useful for testing – inject test doubles  Also helps reduce coupling
  • 11. Shaun Abram 11 Test Doubles Mocks Stubs Dummies Spies Fakes
  • 12. Shaun Abram 12 Test Doubles Mocks Stubs Dummies Spies Fakes
  • 13. Shaun Abram 13 Test Doubles: Mocks Mocks: An overloaded term! uses behavior verification objects pre-programmed with expectations
  • 14. 14
  • 15. 15  Mocks use behavior verification  Can specify how to respond when called  Roll your own?
  • 16. Shaun Abram 16 Test Doubles Mocks Stubs Dummies Spies Fakes
  • 17. Shaun Abram 17 Test Doubles: Stubs ‘stubs out’ or provides a simplified version of the implementation for the purposes of testing
  • 18. 18
  • 19. 19  Stubs can use state or behavior verification  Provides a useful approach for test fixture configurability
  • 20. Shaun Abram 20 Test Doubles Mocks Stubs Dummies Spies Fakes
  • 21. Shaun Abram 21 Test Doubles: Dummies A very dumb class! Contains next to nothing - enough to compile Pass when you don’t expect to be used
  • 22. 22  Use dummies with state or behavior verification  Can create as inner class  Can replicate with mocks
  • 23. Shaun Abram 23 Unit Testing – the tricky parts Legacy code Privates Statics
  • 24. Shaun Abram 24 General approach to testing legacy code 1) Start with coarse grained tests No modifications Strict and rigid Detect regressions Short term bridges - delete
  • 25. Shaun Abram 25 General approach to testing legacy code 1) Start with coarse grained tests 2) Add finer grained tests Incrementally add more unit start gently refactoring Use TDD – if possible Test from 1) should protect you
  • 26. Shaun Abram 26 General approach to testing legacy code 1) Start with coarse grained tests 2) Add finer grained tests 3) Continuously refactor Use patterns such as Extract Method/Class Move Method/Field tease apart methods (>10 lines smells)
  • 27. Shaun Abram 27 Unit Testing – the tricky parts Legacy code Privates Statics
  • 28. Shaun Abram 28 How do you test private methods? Indirectly! Best tested via public interface But sometimes… Legacy code With limited capability to refactor, or adding a safety net before refactoring A public method calls several private methods, each with complex logic
  • 29. Shaun Abram 29 Testing Private Methods 1. Refactor 2. Change the visibility Bad practice Public API? Very bad practice! Internal & stepping stone -> lesser evil Java private -> package; .Net protected or internal? Document (@VisibleForTesting)
  • 30. Shaun Abram 30 Testing Private Methods 1. Refactor 2. Change the visibility 3. Use Reflection No code modification, but… 4. Other options… Testing frameworks InternalsVisibleToAttribute Private Accessors
  • 31. Shaun Abram 31 Testing static methods
  • 32. 32
  • 33. 33
  • 34. 34
  • 35. Shaun Abram 35 Testing static methods DI ideal But sometimes not pragmatic
  • 36. 36
  • 37. 37 Refactor to wrap the static call in an instance method Which can then be mocked…
  • 38. 38
  • 39. 39
  • 40. 40
  • 41. Shaun Abram 41 Testing static methods Refactor – use DI Wrap static call in a instance method Use a mocking framework?
  • 42. Shaun Abram 42 Test Driven Development
  • 43. Shaun Abram 43 Test Driven Development
  • 44. Shaun Abram 44 Test Driven Development
  • 45. Shaun Abram 45 Test Driven Development
  • 46. Shaun Abram 46 Test Driven Development
  • 47. Shaun Abram 47 Test Driven Development Red - Green – Refactor: the TDD Mantra No new functionality without a failing test No refactoring without passing tests
  • 48. Shaun Abram 48 Test Driven Development Example…
  • 49. Shaun Abram 49 Test Driven Development Example… Create a StringCalculator class with an add method which takes a comma separate String of numbers and returns their sum. Example input Result 0 1 1 2 2 1,2 3 1,2,100 103
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 57.
  • 58.
  • 59.
  • 60.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70. These tests act like the original developer looking over your shoulder and advising you, long after that developer has left… These tests act like the original developer looking over your shoulder and advising you, long after that developer has left…
  • 71. Shaun Abram 71 Recommended reading Growing Object-Oriented Software, Guided by Tests Freeman & Pryce Test Driven Development Kent Beck Refactoring: Improving the Design of Existing Code Martin Fowler, Kent Beck et. al. Effective Unit Testing Lasse Koskela
  • 72. Shaun Abram 72 Recommended reading Unit Test Best Practices - https://wiki.tlcinternal.com/display/TD/Unit+Test+Best+Practices Mocks Arent Stubs - http://www.martinfowler.com/articles/mocksArentStubs.html