SlideShare a Scribd company logo
1 of 73
Download to read offline
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

Automação de teste de software
Automação de teste de softwareAutomação de teste de software
Automação de teste de softwareQualister
 
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛ
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛМАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛ
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛЭрдэнэцогт Амар
 
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨР
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨРЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨР
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨРAsel Kunju
 
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦ
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦАРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦ
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦBilgee Zaya
 
эзф судлах зүйл
эзф судлах зүйлэзф судлах зүйл
эзф судлах зүйлyivo1004
 
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх аргаsaruul tungalag
 
Testicular torsion, төмсөг мушгирах
Testicular torsion, төмсөг мушгирахTesticular torsion, төмсөг мушгирах
Testicular torsion, төмсөг мушгирахNaraa Bayarsaikhan
 
Automatisation des tests - objectifs et concepts - partie 2
Automatisation des tests  - objectifs et concepts - partie 2Automatisation des tests  - objectifs et concepts - partie 2
Automatisation des tests - objectifs et concepts - partie 2Christophe Rochefolle
 
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬ
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬБ. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬ
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬbatnasanb
 
Active Directoryデータの Security Descriptor
Active Directoryデータの Security DescriptorActive Directoryデータの Security Descriptor
Active Directoryデータの Security DescriptorMichio Koyama
 
Choosing the right QA strategy for a successful project
Choosing the right QA strategy for a successful projectChoosing the right QA strategy for a successful project
Choosing the right QA strategy for a successful projectThe Software House
 

What's hot (20)

Варикоцеле
ВарикоцелеВарикоцеле
Варикоцеле
 
Automação de teste de software
Automação de teste de softwareAutomação de teste de software
Automação de teste de software
 
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛ
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛМАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛ
МАЛЫН МАХНЫ ЗОХИЦУУЛАГЧ ҮЙЛЧЛЭЛИЙН ҮНДЭСЛЭЛ
 
Emnelzuin emgeg sudlal
Emnelzuin emgeg sudlalEmnelzuin emgeg sudlal
Emnelzuin emgeg sudlal
 
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨР
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨРЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨР
ЭДИЙН ЗАСГИЙН ОНОЛ ХИЧЭЭЛИЙН СТАНДАРТ ХӨТӨЛБӨР
 
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦ
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦАРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦ
АРИЛЖААНЫ БАНКНЫ САНХҮҮГИЙН ТАЙЛАНГИЙН БҮТЭЦ
 
эзф судлах зүйл
эзф судлах зүйлэзф судлах зүйл
эзф судлах зүйл
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга
8. Гэр бүл төлөвлөлт, жирэмслэлтээс урьдчилан сэргийлэх арга
 
Intussusception
IntussusceptionIntussusception
Intussusception
 
Testicular torsion, төмсөг мушгирах
Testicular torsion, төмсөг мушгирахTesticular torsion, төмсөг мушгирах
Testicular torsion, төмсөг мушгирах
 
Automatisation des tests - objectifs et concepts - partie 2
Automatisation des tests  - objectifs et concepts - partie 2Automatisation des tests  - objectifs et concepts - partie 2
Automatisation des tests - objectifs et concepts - partie 2
 
кальци
кальцикальци
кальци
 
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬ
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬБ. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬ
Б. Нармандах - БИЧИЛ БИЗНЕСИЙГ АЖИЛЛАГААГ ДЭМЖИХ НЬ
 
ЖЮ85092367.pdf
ЖЮ85092367.pdfЖЮ85092367.pdf
ЖЮ85092367.pdf
 
цус задрах хам шинж
цус задрах хам шинж  цус задрах хам шинж
цус задрах хам шинж
 
Active Directoryデータの Security Descriptor
Active Directoryデータの Security DescriptorActive Directoryデータの Security Descriptor
Active Directoryデータの Security Descriptor
 
Mac ecs1.2021h
Mac ecs1.2021hMac ecs1.2021h
Mac ecs1.2021h
 
Laboratoriin tehnikch
Laboratoriin tehnikchLaboratoriin tehnikch
Laboratoriin tehnikch
 
Choosing the right QA strategy for a successful project
Choosing the right QA strategy for a successful projectChoosing the right QA strategy for a successful project
Choosing the right QA strategy for a successful project
 

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

oracle 23c new features for developer and dba
oracle 23c new features for developer and dbaoracle 23c new features for developer and dba
oracle 23c new features for developer and dbaRemote DBA Services
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxAS Design & AST.
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...OnePlan Solutions
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
Business Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisBusiness Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisDEEPRAJ PATHAK
 
Santander Stream Processing with Apache Flink
Santander Stream Processing with Apache FlinkSantander Stream Processing with Apache Flink
Santander Stream Processing with Apache Flinkconfluent
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsDEEPRAJ PATHAK
 

Recently uploaded (20)

oracle 23c new features for developer and dba
oracle 23c new features for developer and dbaoracle 23c new features for developer and dba
oracle 23c new features for developer and dba
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
Transform your Corporate Strategy Office - Harness OnePlan’s Strategic Portfo...
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
Business Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business AnalysisBusiness Analyzopedia - Your Pocket Gita for Business Analysis
Business Analyzopedia - Your Pocket Gita for Business Analysis
 
Santander Stream Processing with Apache Flink
Santander Stream Processing with Apache FlinkSantander Stream Processing with Apache Flink
Santander Stream Processing with Apache Flink
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software Projects
 

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