SlideShare a Scribd company logo
Unit TestingPractical Tips
In the beginningFirst testing experience
Why Unit Testing?Instead of starting by Testing Manually, you start by testing programmatically.You test the code once…… and then continuously afterwards.Guards against others breaking your code.Guards against regression errors.Refactoring RuthlesslyPeace of Mind
Types of Testing – All ImportantFunctional Testing (manual)Integration Testing (automated)(Dosens)SlowUnit Testing (automated)(Hundreds)Localize FailuresFastDynamic Language DebuggersUI LayerPerson ViewPerson ControllerPerson ModelLogic LayerSecurity ManagerData Layer
Test-First of Test-After?The difference is only When you write your tests?Test-After is painful and boring.Test-First makes unit testing easier. Unit Testing == Good. Win win situation.Test-Driven-DesignTest-First drives the Design – Low Coupling.Write only enough to make the test pass.YAGNI
Automatic Test Generation?Only possible after the code has been written.You won’t get tests like…Test_that_user_registration_fails_on_invalid_ID()Doesn’t test Intent, can only test Methods.
Why testing efforts failWhen tests become frustratingIntegration Tests != Unit TestsSlowBrittle – break unnecessarilyHard to Write due to highly coupled code.
Let’s test some code
What to test?Single Responsibility PrincipleTest the responsibility of the Controller Action.ApplicationSuccess view should be returned if application succeeds.ApplicationFailure view should be returned with a reason if application fails.
Our “Unit Test”DatabaseWeb ServiceSession State
Step 1: Extract ClassSingle Responsibility PrincipleController – Return correct view and viewModel
UserCreditService – Contains user credit checking functionsStep 2: Use fake Repository and fake UserCreditServiceFake objects replace the functionality of the of the real object with an alternate implementaiton, ie returning a canned list of values instead of hitting a databaseTest Stub is an object that is used by a test to replace a real component to force the system down the path we want for the test. A stub may also record info about how it was called (ie. stub.wasMethodCalled())Mocks fake implementation by returning hard coded values or values preloaded - they can also verify that the correct calls were made in the right order
Injecting Fakes ControllerTestTests…Creates…Fake DBRepoControllerUses…Fake DBRepo
Step 2: Fake object and Dependency Injection
Step 2: Fake object and dependency injection
Step 3: Abstract and Mock SessionA Mock Example…Specify behaviours
Specify expectations
Works for Interfaces, Abstracts and VirtualsStep 3: Abstract and Mock Session
Step 3: Abstract and Mock Session
Tips
Tip: A handy private class
TipFine grained is better100 tests that test 100 things is better… than 10 tests that test a 100 things.Execute the same action many times in different tests and verify different results in each call.Makes errors easier to isolate.
TipsBreak Dependencies – strive for low couplingUse Dependency InjectionAvoid public StaticsAvoid SingletonsUse Interfaces to abstract calls to other classesUse Mocks to mimic and test behaviourSingle Responsibility Principle – break things into smaller classes and test independently.
Ad

More Related Content

What's hot (20)

Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
dunglinh111
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
Shaun Abram
 
White box testing
White box testing White box testing
White box testing
Mani Kanth
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
Frank Appel
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Joe Tremblay
 
Quality Software With Unit Test
Quality Software With Unit TestQuality Software With Unit Test
Quality Software With Unit Test
alice yang
 
Debugging
DebuggingDebugging
Debugging
Imran Memon
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Automation test
Automation testAutomation test
Automation test
yuyijq
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
Brian Fenton
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
Dave Bouwman
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
ikhwanhayat
 
5 black box and grey box testing
5   black box and grey box testing5   black box and grey box testing
5 black box and grey box testing
Yisal Khan
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Anuj Arora
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
Lee Englestone
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
dunglinh111
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
Shaun Abram
 
White box testing
White box testing White box testing
White box testing
Mani Kanth
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
Frank Appel
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Joe Tremblay
 
Quality Software With Unit Test
Quality Software With Unit TestQuality Software With Unit Test
Quality Software With Unit Test
alice yang
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Automation test
Automation testAutomation test
Automation test
yuyijq
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
Brian Fenton
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
ikhwanhayat
 
5 black box and grey box testing
5   black box and grey box testing5   black box and grey box testing
5 black box and grey box testing
Yisal Khan
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
Lee Englestone
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 

Similar to Practical unit testing tips (20)

TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
Attila Bertók
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
Priya Sharma
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
David Rogers
 
Unit testing
Unit testingUnit testing
Unit testing
Murugesan Nataraj
 
Test driven development
Test driven developmentTest driven development
Test driven development
namkha87
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
Renato Primavera
 
Real Life Unit Testing
Real Life Unit TestingReal Life Unit Testing
Real Life Unit Testing
Dror Helper
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
Ferdous Mahmud Shaon
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Cefalo
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere Mortals
Jess Chadwick
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
Alejandro Claro Mosqueda
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Mocking
MockingMocking
Mocking
eleksdev
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
Francesco Garavaglia
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
Test driven development
Test driven developmentTest driven development
Test driven development
namkha87
 
Real Life Unit Testing
Real Life Unit TestingReal Life Unit Testing
Real Life Unit Testing
Dror Helper
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
Ferdous Mahmud Shaon
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Cefalo
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
Automated Unit Testing for Mere Mortals
Automated Unit Testing for Mere MortalsAutomated Unit Testing for Mere Mortals
Automated Unit Testing for Mere Mortals
Jess Chadwick
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Ad

Recently uploaded (20)

AI and Gender: Decoding the Sociological Impact
AI and Gender: Decoding the Sociological ImpactAI and Gender: Decoding the Sociological Impact
AI and Gender: Decoding the Sociological Impact
SaikatBasu37
 
Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Right to liberty and security of a person.pdf
Right to liberty and security of a person.pdfRight to liberty and security of a person.pdf
Right to liberty and security of a person.pdf
danielbraico197
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More MachinesRefactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Leon Anavi
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
AI and Gender: Decoding the Sociological Impact
AI and Gender: Decoding the Sociological ImpactAI and Gender: Decoding the Sociological Impact
AI and Gender: Decoding the Sociological Impact
SaikatBasu37
 
Cybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft CertificateCybersecurity Tools and Technologies - Microsoft Certificate
Cybersecurity Tools and Technologies - Microsoft Certificate
VICTOR MAESTRE RAMIREZ
 
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Who's choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Right to liberty and security of a person.pdf
Right to liberty and security of a person.pdfRight to liberty and security of a person.pdf
Right to liberty and security of a person.pdf
danielbraico197
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More MachinesRefactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Refactoring meta-rauc-community: Cleaner Code, Better Maintenance, More Machines
Leon Anavi
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptxUiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
UiPath AgentHack - Build the AI agents of tomorrow_Enablement 1.pptx
anabulhac
 
Best 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat PlatformsBest 10 Free AI Character Chat Platforms
Best 10 Free AI Character Chat Platforms
Soulmaite
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Ad

Practical unit testing tips

  • 2. In the beginningFirst testing experience
  • 3. Why Unit Testing?Instead of starting by Testing Manually, you start by testing programmatically.You test the code once…… and then continuously afterwards.Guards against others breaking your code.Guards against regression errors.Refactoring RuthlesslyPeace of Mind
  • 4. Types of Testing – All ImportantFunctional Testing (manual)Integration Testing (automated)(Dosens)SlowUnit Testing (automated)(Hundreds)Localize FailuresFastDynamic Language DebuggersUI LayerPerson ViewPerson ControllerPerson ModelLogic LayerSecurity ManagerData Layer
  • 5. Test-First of Test-After?The difference is only When you write your tests?Test-After is painful and boring.Test-First makes unit testing easier. Unit Testing == Good. Win win situation.Test-Driven-DesignTest-First drives the Design – Low Coupling.Write only enough to make the test pass.YAGNI
  • 6. Automatic Test Generation?Only possible after the code has been written.You won’t get tests like…Test_that_user_registration_fails_on_invalid_ID()Doesn’t test Intent, can only test Methods.
  • 7. Why testing efforts failWhen tests become frustratingIntegration Tests != Unit TestsSlowBrittle – break unnecessarilyHard to Write due to highly coupled code.
  • 9. What to test?Single Responsibility PrincipleTest the responsibility of the Controller Action.ApplicationSuccess view should be returned if application succeeds.ApplicationFailure view should be returned with a reason if application fails.
  • 10. Our “Unit Test”DatabaseWeb ServiceSession State
  • 11. Step 1: Extract ClassSingle Responsibility PrincipleController – Return correct view and viewModel
  • 12. UserCreditService – Contains user credit checking functionsStep 2: Use fake Repository and fake UserCreditServiceFake objects replace the functionality of the of the real object with an alternate implementaiton, ie returning a canned list of values instead of hitting a databaseTest Stub is an object that is used by a test to replace a real component to force the system down the path we want for the test. A stub may also record info about how it was called (ie. stub.wasMethodCalled())Mocks fake implementation by returning hard coded values or values preloaded - they can also verify that the correct calls were made in the right order
  • 13. Injecting Fakes ControllerTestTests…Creates…Fake DBRepoControllerUses…Fake DBRepo
  • 14. Step 2: Fake object and Dependency Injection
  • 15. Step 2: Fake object and dependency injection
  • 16. Step 3: Abstract and Mock SessionA Mock Example…Specify behaviours
  • 18. Works for Interfaces, Abstracts and VirtualsStep 3: Abstract and Mock Session
  • 19. Step 3: Abstract and Mock Session
  • 20. Tips
  • 21. Tip: A handy private class
  • 22. TipFine grained is better100 tests that test 100 things is better… than 10 tests that test a 100 things.Execute the same action many times in different tests and verify different results in each call.Makes errors easier to isolate.
  • 23. TipsBreak Dependencies – strive for low couplingUse Dependency InjectionAvoid public StaticsAvoid SingletonsUse Interfaces to abstract calls to other classesUse Mocks to mimic and test behaviourSingle Responsibility Principle – break things into smaller classes and test independently.
  翻译: