SlideShare une entreprise Scribd logo
1  sur  32
Testing the Untestable Taming production code Roy Klein Flash Client Team Leader Wix.com
Overview Test Driven Development Overview The motivations for and challenges of testing our production code Techniques + a real life example
Unit Testing Exercise classes in an isolated environment Verify that actions on the code produce predictable, consistent results Write Tests Write Code Pass All Tests Refactor
The price of Unit Testing  New logic is more time consuming to write Old logic may require extensive Refactoring to be testable Amount of code to maintain increases Illusion of being bug free when tests pass No Stage in FlexUnit The actual visual output can’t be fully tested
The benefits of Unit Testing Better definition and understanding of the code’s purpose Helps improve code design Empowers refactoring Documents the usage of the code A small, quick environment to debug in Provides immediate feedback when the code changes (Adding/modifying functionality, Refactoring, Merging)
TDD ROI conclusions The price: Initial additional development time The benefit: Cumulative reduction in defects The conclusion: No brainer for long term projects
The Challenges Classes and functions have multiple responsibilities Classes are strongly coupled to other classes Some of these couplings are to Singletons Ambiguous dependencies (Objects, callbacks) In short, code changes have unknown side effects that are hard to foresee
The Motivation Our production code is the result of several years of  rat chase Rapid Development Refactoring core code is dangerous Augmenting core capabilities is expensive Reducing code volatility may save us from a dangerous rewrite, or allow us to reuse code when a rewrite occurs Moving to CI is key to remaining competitive
Legacy Testing Heuristic  Before making the change, write passing tests for the area around your change These tests are intended to preserve the behavior of the code prior to your change Add failing tests that define the change you’re making Apply your change and make all tests pass
Replace Dialog: Dependency Breaking
Replace Dialog: Dependency Breaking
Case Study 1: Replace Gallery
Safe Modification: Function extraction Preserve the original functions’ signature.
1. Preserve function signature
Safe Modification: Function extraction Preserve the original functions’ signature.  Extract the function to its own class
2. Extract the modified function
Safe Modification: Function extraction Preserve the original functions’ signature.  Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class
3. Reference original class
Safe Modification: Function extraction Preserve the original functions’ signature.  Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class
4. Use IDE to find what’s missing
Safe Modification: Function extraction Preserve the original functions’ signature.  Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class Put those calls in the interface
5. Put what’s missing in the interface
5. Put what’s missing in the interface
Safe Modification: Function extraction Preserve the original functions’ signature.  Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class Put those calls in the interface Create a mock class implementing the interface for testing
6. Create a mock class
Test can now execute!
Breaking encapsulation on purpose Encapsulation is a tool that makes the code usage easier to understand The need to break it often points to problem in the design of the code usage Problems in design can’t be solved without Unit Tests in place The break can help in understanding what needs to be changed Damage can be minimized with self documenting code
Breaking encapsulation on purpose
Solving Singletons dependency You can’t use a testing instance Create a testing only function to set a testing instance
Solving Static dependencies You can’t subclass or mock a static class Replace reference to static variables with getters and static functions to local functions Subclass and override with a test class to use your own data/logic In case of a massive amount of static calls, use the same class name in your testing project to override the original class, and delegate all calls to another class
Conclusion Getting legacy code into a testing environment is possible Most of the benefits of TDD can be achieved with partial coverage Adapting TDD during any stage of the development is worthwhile. The bigger the project, the more beneficial it is
Q & A ,[object Object]

Contenu connexe

Tendances

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010guest5639fa9
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Kaunas Java User Group
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefAhmed Shreef
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Code review
Code reviewCode review
Code reviewdqpi
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 
A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) CodeOps Technologies LLP
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard partsShaun Abram
 
Behaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowBehaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowPascal Laurin
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowRachid Kherrazi
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief exampleJeremy Kendall
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Automated testing - how?
Automated testing - how?Automated testing - how?
Automated testing - how?Markko Paas
 

Tendances (19)

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010Test Driven Development (TDD) Preso 360|Flex 2010
Test Driven Development (TDD) Preso 360|Flex 2010
 
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
Bye Bye Cowboy Coder Days! (Legacy Code & TDD)
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Code review
Code reviewCode review
Code review
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD) A Not-So-Serious Introduction to Test Driven Development (TDD)
A Not-So-Serious Introduction to Test Driven Development (TDD)
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Behaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlowBehaviour Driven Development with SpecFlow
Behaviour Driven Development with SpecFlow
 
Behavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlowBehavior Driven Development with SpecFlow
Behavior Driven Development with SpecFlow
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief example
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Automated testing - how?
Automated testing - how?Automated testing - how?
Automated testing - how?
 

Similaire à Testing the untestable

Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminardunglinh111
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionPyxis Technologies
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonSeb Rose
 
Odd E验收测试驱动开发实战
Odd E验收测试驱动开发实战Odd E验收测试驱动开发实战
Odd E验收测试驱动开发实战George Ang
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Myeongseok Baek
 
Making the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingMaking the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingCameron Presley
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
How To Tidy Up Your Test Code
How To Tidy Up Your Test CodeHow To Tidy Up Your Test Code
How To Tidy Up Your Test CodeRock Interview
 
Selenium Design Patterns
Selenium Design PatternsSelenium Design Patterns
Selenium Design PatternsLiraz Shay
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Kevin Schultz
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioAmit Choudhary
 
Comfortable code
Comfortable codeComfortable code
Comfortable codeRemus Langu
 
Implementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsImplementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsAhmad Kazemi
 

Similaire à Testing the untestable (20)

Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse Refactor
 
JavaScript Unit Testing
JavaScript Unit TestingJavaScript Unit Testing
JavaScript Unit Testing
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and Adoption
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking Skeleton
 
Odd E验收测试驱动开发实战
Odd E验收测试驱动开发实战Odd E验收测试驱动开发实战
Odd E验收测试驱动开发实战
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 
Design pattern
Design patternDesign pattern
Design pattern
 
Making the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingMaking the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To Testing
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
How To Tidy Up Your Test Code
How To Tidy Up Your Test CodeHow To Tidy Up Your Test Code
How To Tidy Up Your Test Code
 
Selenium Design Patterns
Selenium Design PatternsSelenium Design Patterns
Selenium Design Patterns
 
Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)Building Maintainable Android Apps (DroidCon NYC 2014)
Building Maintainable Android Apps (DroidCon NYC 2014)
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Comfortable code
Comfortable codeComfortable code
Comfortable code
 
Implementing TDD in for .net Core applications
Implementing TDD in for .net Core applicationsImplementing TDD in for .net Core applications
Implementing TDD in for .net Core applications
 

Dernier

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Dernier (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Testing the untestable

  • 1. Testing the Untestable Taming production code Roy Klein Flash Client Team Leader Wix.com
  • 2. Overview Test Driven Development Overview The motivations for and challenges of testing our production code Techniques + a real life example
  • 3. Unit Testing Exercise classes in an isolated environment Verify that actions on the code produce predictable, consistent results Write Tests Write Code Pass All Tests Refactor
  • 4. The price of Unit Testing New logic is more time consuming to write Old logic may require extensive Refactoring to be testable Amount of code to maintain increases Illusion of being bug free when tests pass No Stage in FlexUnit The actual visual output can’t be fully tested
  • 5. The benefits of Unit Testing Better definition and understanding of the code’s purpose Helps improve code design Empowers refactoring Documents the usage of the code A small, quick environment to debug in Provides immediate feedback when the code changes (Adding/modifying functionality, Refactoring, Merging)
  • 6. TDD ROI conclusions The price: Initial additional development time The benefit: Cumulative reduction in defects The conclusion: No brainer for long term projects
  • 7. The Challenges Classes and functions have multiple responsibilities Classes are strongly coupled to other classes Some of these couplings are to Singletons Ambiguous dependencies (Objects, callbacks) In short, code changes have unknown side effects that are hard to foresee
  • 8. The Motivation Our production code is the result of several years of rat chase Rapid Development Refactoring core code is dangerous Augmenting core capabilities is expensive Reducing code volatility may save us from a dangerous rewrite, or allow us to reuse code when a rewrite occurs Moving to CI is key to remaining competitive
  • 9. Legacy Testing Heuristic Before making the change, write passing tests for the area around your change These tests are intended to preserve the behavior of the code prior to your change Add failing tests that define the change you’re making Apply your change and make all tests pass
  • 12. Case Study 1: Replace Gallery
  • 13. Safe Modification: Function extraction Preserve the original functions’ signature.
  • 14. 1. Preserve function signature
  • 15. Safe Modification: Function extraction Preserve the original functions’ signature. Extract the function to its own class
  • 16. 2. Extract the modified function
  • 17. Safe Modification: Function extraction Preserve the original functions’ signature. Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class
  • 19. Safe Modification: Function extraction Preserve the original functions’ signature. Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class
  • 20. 4. Use IDE to find what’s missing
  • 21. Safe Modification: Function extraction Preserve the original functions’ signature. Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class Put those calls in the interface
  • 22. 5. Put what’s missing in the interface
  • 23. 5. Put what’s missing in the interface
  • 24. Safe Modification: Function extraction Preserve the original functions’ signature. Extract the function to its own class Call the new function with the same signature, and a reference to an interface representing the original class Use the IDE to determine what calls are to be redirected to the original class Put those calls in the interface Create a mock class implementing the interface for testing
  • 25. 6. Create a mock class
  • 26. Test can now execute!
  • 27. Breaking encapsulation on purpose Encapsulation is a tool that makes the code usage easier to understand The need to break it often points to problem in the design of the code usage Problems in design can’t be solved without Unit Tests in place The break can help in understanding what needs to be changed Damage can be minimized with self documenting code
  • 29. Solving Singletons dependency You can’t use a testing instance Create a testing only function to set a testing instance
  • 30. Solving Static dependencies You can’t subclass or mock a static class Replace reference to static variables with getters and static functions to local functions Subclass and override with a test class to use your own data/logic In case of a massive amount of static calls, use the same class name in your testing project to override the original class, and delegate all calls to another class
  • 31. Conclusion Getting legacy code into a testing environment is possible Most of the benefits of TDD can be achieved with partial coverage Adapting TDD during any stage of the development is worthwhile. The bigger the project, the more beneficial it is
  • 32.
  • 33. Working Effectively With Legacy Code: Michael FeathersFurther reading:

Notes de l'éditeur

  1. אני אעבור מאוד בקצרה על יוניט טסטינג, יתרונות, חסרונות, אח"כ אני אספר קצת על הרקע להחלטה של שינוי מתודולוגיית הפיתוח, וההשלכות המקצועיות של ההחלטה הזו, ולבסוף אני אעבור על טכניקות פיתוח של הכנסת קוד שעל פניו נראה בלתי אפשרי לבדיקה, לתוך סביבת בדיקה בצורה בטוחה, בלי לשנות את ההתנהגות שלו בתהליך, עם דוגמה אמיתית ממצולות הקוד בייס של וויקס.
  2. אז קודם כל קצת על יוניט טסטינג, האבן יסוד של TDD. על רגל אחת, מדובר על קוד שמריץ קוד ובודק את התוצאות בהנתן כל מני אינפוטים.בתחילת כל טסט, אינסנטס חדש של הקלאס נוצר, ופעולה אחת בלבד מתבצעת – בד"כ קיראה לפונקציה עם ערך כלשהו. לבסוף, בודקים שהפעולה גרמה לתוצאה הצפויה. אם כן, הטסט עובר. אם לא, הטסט נכשל.הסייקל פיתוח ב TDDהוא פחות או יותר ככה: מפתח כותב פעולה אטומית, שיכולה להיות פיצ'ר, חלק מפיצ'ר, תיקון באג, בד"כ לא יותר מכמה שורות קוד, ובמבקביל כותב טסטים או מתקן טסטים כדי לבדוק שהקוד שהוא הרגע כתב עושה מה שהוא אמור לעשות. בגישה הקלאסית אומרים תמיד לכתוב הטסט קודם ואז את הקוד הפשוט ביותר שגורם לטסט הזה לעבור, אבל אני לא דוגמטי לגבי הסדר, וכך גם רוב מפתחי ה TDD שדיברתי איתם.אחרי שהפיצ'ר כתוב וכל הטסטים כתובים ועוברים, אפשר לשכתב את הקוד כך שיהיה יותר יפה או יותר יעיל. כיוון שיש לנו טסטים שמוודאים את תקינות הקוד, אנחנו חופשיים לשכתב בסייקלים מאוד מהירים ובלי המון מחשבה על שינוי פוקציונליות, אם עשינו טעות, לפחות טסט אחד אמור להכשל, ומייד יש לנו פידבק שעשינו טעות.ולבסוף, כמובן חוזרים וממשיכים בכתיבה של פעולה אטומית חדשה.
  3. אני לא אעבור על כל הנקודות, רק אציין שבגדול אפשר לומר שזמן הפיתוח מתארך כשעובדים עם טסטים. מן הסתם, מדובר בעוד קוד שצריך לכתוב.יוניט טסטים גם לא נועדו לבדוק ממשק או תוצאות ויזואליות. לדוגמא, המנגנון צביעה של וויקס נבדק ע"י טסטים בכל שלב בתהליך, חוץ מהאם באמת בסוף אובייקטים נצבעו כמו שהם אמורים להצבע.
  4. כל הנקודות האלה מסתכמות פחות או יותר בכך שלאורך זמן, כמות הבאגים שהמוצר צובר פחותה בהרבה ביחס לפיתוח ללא טסטינג. זוהי נקודה שנבדקה ע"י מספר מחקרים ונמצאה כנכונה.
  5. אז החסרון העיקרי של יוניט טסטינג זה זמן פיתוח ראשוני ארוך יותר, והיתרון העיקרי של יוניט טסטינג זה ירידה משמעותית בהצטברות באגים. אז לפרוייקטים ארוכי טווח, עבודה עם יוניט טסטים צריכה להיות החלטה יד מובנת מאליה.י
  6. עם קצת נסיון ביוניט טסטינג, בדיקה של קוד חדש היא עניין של מה בכך. האתגר הטכני הוא, כיצד בודקים קוד ישן שצריך לבצע בו שינויים? קלאסים שלא נכתבו במתודולוגיה של טסטים נוטים להיות מאוד תלותיים בקלאסים אחרים, פשוט כי יותר טבעי לכתוב עם תלות מאשר בלי. הנה דוגמה מהקוד בייס שלנו. לאחרונה הכנסנו את האדיטור שלנו לתוך מעטפת פלקס, מתוך כוונה להמיר לאט לאט את ה UI שלנו לפלקס. יש לנו דיאלוג להוספת אייטמים, שמשתמשים בה בהרבה מקומות במוצר, ובין השאר מתוך דיאלוג שהומר לפלקס. כדי לפתור כל מני בעיות, היינו צריכים שהדיאלוג הוספה הזה, כשהוא נפתח מהדיאלוג הפלקסי, ייפתח בתוך מעטפת פלקסית גם הוא. הקוד שפותח את הדיאלוג הוספה נמצא בתוך קלאס מאוד ישן ומאוד גדול, שנקרא EdWizardManager
  7. אנחנו בוויקס עובדים על פרוייקט ארוך טווח, ולא אימצנו טסטינג מתחילת הדרך. בתחילת קיומה, כמו כל סטארט אפ, וויקס היתה במירוץ כנגד השעון, להגיע למוצר מוכר לפני שכסף ההשקעה זולג או שמתחרים משתלטים על השוק עם מוצר מתחרה. הפיתוח המאוד מהיר הוכיח את עצמו בסופו של דבר, כשוויקס הצליחה לצאת מנצחת עם מוצר מוביל בשוק, אבל הקוד בייס של המוצר הגיע למצב שהיה ריסקי לבצע בו שינויים. מצד אחד המון לקוחות תלויים ביציבות שלו, ומצד שני הוא לא כתוב בצורה שנותנת פידבק על תוצאה של שינויים. גרסאות התחילו להתארך ולהסתבך, הQA נהיה תהליך יקר, והבנו שכדי להתקדם בצורה משמעותית מעתה והלאה, צריך לשנות את תפיסת הפיתוח.בהתחלה הוחלט על שכתוב. נשכרו אנשים והוקם צוות שהתחיל לעבוד על וויקס 2, אבל באותה תקופה גם התחילה הפניקה בתעשייה מהמהלך המוצהר של אפל כנגד פלאש. וויקס לא רצתה להשאר מחוץ לשוק ההולך וגדל של האייפונים, והוחלט לנטוש את עבודת השכתוב, לטובת כתיבת מוצר חדש שנותן שירות בניית אתרים דומה לוויקס בפלאש, אבל ב HTML. למרות שבאותה תקופה האמנתי בשכתוב, וגם רציתי להיות מעורב בשכתוב מתוך עניין מקצועי, בדיעבד אני מאוד שמח שנמנענו מזה. הסיכון והעלויות של שכתוב מוצר הם עצומים, ולאחר ששינינו את תפיסת הפיתוח על המוצר הקיים, הסתבר גם שהרבה מהבעיות של הקוד בייס המקורי הן פתירות. אז שינינו את תפיסת הפיתוח. הוחלט לאמץ בכל מחלקות הR&D חזון של CI, קוניטינוס אינטגריישן. בשביל הפלאש קליינט, שנכתב במתודולוגיה הפוכה לחלוטין לזו של CI, היינו די פסיימים בהתחלה. איך נגיע אי פעם לCI, אם אפילו כיסוי חלקי של המערכת בטסטים נראה בלתי אפשרי? אבל גילינו שכיסוי של שינויים מביא את עיקר התועלת, כך שמה שלא משתנה ונשאר לא בדוק, הוא לא פקטור, כל עוד השינויים החדשים כן בדוקים.
  8. לפני שכתבתי את השינוי, רציתי לבדוק אם אני יכול בכלל לשים את הקוד הזה בסביבת בדיקה. כמו שאתם רואים, כבר בקונסטרקטור הקלאס הזה צריך כל מני תלויות שלא קשורות בכלל לשינוי שאני הולך לעשות.
  9. החלטתי לאמץ גישה אופטימית. הקוד שאני רוצה לשנות לא תלוי בדברים האלה, אז אם הקלאס יווצר כשהדברים האלה הם נאל, מה טוב. הוספתי טסט שלא עושה כלום, רק כדי לראות שהיצירה של הקלאס עוברת בלי תקלות.
  10. הגישה האופטימית נחלה כשלון במקרה הזה. אפילו טסט ריק לא מצליח לרוץ בלי תקלות , בגלל שעצם היצירה של הקלאס צריכה אובייקטים אחרים, שאולי גם הם צריכים אובייקטים כדי להווצר כמו שצריך.היתה לי בנקודה הזו כמה אפשרויות: או לשנות את הקונסטרקטור של הקלאס כדי שאני אוכל ליצור אותו בלי תלויות, או לשנות את הטיפוסים כדי שאני אוכל ליצור את הקלאס עם זיופים של התלויות, או להוציא את הקוד שאני עובד עליו מהקלאס.מכל האפשרויות האלה, האחרונה היתה הכי פשוטה וכללה שינויים במקומות שאני רוצה לשנות בכל מקרה. האחרות כללו שינויים שלא קשורים בכלל לשינוי שאני רוצה, וגם נשמעו לי כמו שינויים הרבה יותר מסוכנים