SlideShare une entreprise Scribd logo
1  sur  35
Unit Tests = Maintenance Hell ?

Thibaud DESODT
@tsimbalar
This talk
• About Unit-Testing
– Why we do it
– Why it can slow you down
– How to ease the maintenance

• Include :
– .NET-based examples / tools
– … can be applied to other platforms
UNIT TESTS
Value of Unit tests
• Benefits
Value of Unit tests

–
–
–
–
–
“toy”
projects

Avoid introducing bugs
Executable documentation
Regression detection
Know when to stop
Reduce fear / allow
refactoring
–…

Unit-tests help build CONFIDENCE

Codebase size
But when the codebase grows …
Quantity of Test Code
• Prod Code vs Test Code Ratio
– from 1:1 to 1:5 !

More Test Code than Prod Code !
• Muliplied efforts :
– New Code
– Changing existing code
Lower Quality of Test Code
• Viewed as less important than Prod Code
– “Write Once”
– Duplication / Copy+Paste
– Less refactoring / improvements
– Hard to read/understand

• Technical Debt reduction has less priority
Cost of Unit tests

Cost of Unit Tests

Unit-tests introduce FRICTION

Codebase size
Value vs Cost of Unit tests

ROI
WTF?

Codebase size
Unit Tests = Maintenance Hell ?
It can be … but it does not have to !
Value vs Cost of Unit tests

ROI
WTF?

Codebase size
Maintainability of codebase

Solution 1 : give up on Unit Tests
“Legacy Code is code without Tests”
Michael Feathers
Working Effectively with Legacy Code

Codebase size
WIN !

Value vs Cost of Unit tests

Solution 2 : reduce the cost
of test maintenance !

Codebase size
REDUCING TEST MAINTENANCE
COSTS
TIP #1 : GET PROPER TOOLS
Tools to manage thousands of tests
–
–
–
–

Exploring tests / results
Run All
Run/Debug Current Test
Run All Tests in current
Test Class
– Re-run last executed
tests
–…

• VS2012 Test Explorer
– Just kidding !

• Telerik JustCode
• JetBrains ReSharper
Continuous Testing
• NCrunch !
–
–
–
–

Runs tests continuously
Reports results without rebuilding or saving the files !
Impacted tests are run first
Tests run in parallel

• Expensive but worth it ! (159$/289$)
– Give it a try http://www.ncrunch.net/
– Free alternative : http://continuoustests.com/
TIP #2 : GET ORGANIZED
Define conventions
Convention

Choice

Test Projects

[ProjectNamespace].Tests

Test Classes

One/class to test: [TestedClass]Test

Test Methods

[MethodName]_with_[Condition]_[ExpectedOutcome]

Structure

Arrange/Act/Assert or Given/When/Then

Helper methods In Test Class (private static)
In Test Project in namespace TestUtils
In dedicated project « Test Support »

Which convention you choose does not matter,
as long as it’s used by everybody !
Use « standard » variable names /
prefixes
• Common concepts :
– sut (System Under Test)
– actual (result of the action)
– expected (expected value for the result)

• Benefits :
– Makes tests more homogenous
– No need to think of it when writing the test
– Resistant to class renaming !
Typical structure
[TestMethod]
public void SomeMethod_with_SomeConditions_must_DoSomething()
{
// Arrange
var sut = MakeSut();
var expected = "what it should return";
// Act
var actual = sut.DoSomething();
// Assert
Assert.AreEqual(expected, actual, "Should have done something");
}
TIP #3 : MAKE WRITING TESTS
CHEAP AND EASY !
Use templates / snippets
• Commonly created items :
– Test Class
– Test Methods
– Test Helper Methods

• … and share them with the team !
• Examples :
– aaa, aae, any …
TIP #4 : MAKE YOUR TESTS
REFACTORING-FRIENDLY
It will change !
“The only constant is change”
Heraclitus of Ephesus
5th century BC

• In 3 minutes / days / weeks …
• Be ready !
Constructors
• Dependency Injection entry point
– Changes when dependencies are added/removed
– Impact in every test !

• Encapsulate it in a helper Method
MakeSut()
private static ClassToTest MakeSut(
IDependency1 dep1 = null,
IDependency2 dep2 = null)
{
dep1 = dep1 ?? new Mock<IDependency1>().Object;
dep2 = dep2 ?? new Mock<IDependency2>().Object;
return new ClassToTest(dep1, dep2);
}

– Default value for dependencies
– Adding dependencies does not impact tests
Test Data creation
• Classes will change
– New properties
– Updated constructors ….

• Automate generation of « auxiliary » test
objects
AutoFixture
• Creates instances of
classes

var fixture = new Fixture();
var user = fixture.Create<User>();

– Populates constructor
arguments
– Populates properties
– Recursive
– Values derived from
Property names

> Install-Package AutoFixture
https://github.com/AutoFixture/AutoFixture/wiki/Cheat-Sheet
Test-specific comparison
• Comparing objects is common
– Actual vs expected
– Should not override Equals() for the tests

• Adding properties can break comparison
Semantic Comparison
var actualUser = new User(12, "john@rambo.com");
var expectedUser = new User(13, "tibo@desodt.com");
actualUser.AsSource().OfLikeness<User>().ShouldEqual(expectedUser);
Ploeh.SemanticComparison.LikenessException: The provided value
ProductionCode.Lib.Data.User did not match the expected value
ProductionCode.Lib.Data.User. The following members did not match:
- Id.
- EmailAddress.

actualUser.AsSource().OfLikeness<User>()
.Without(u=> u.Id)
.ShouldEqual(expectedUser);

> Install-Package SemanticComparison
TO CONCLUDE
Working with many Unit Tests
• … is hard
• Requires extra care
– Up-front
– During code maintenance

• But pain can be reduced
by:
– Appropriate tools
– Good habits

TIPS
#1 Proper Tools
– Good Test Runner
– Continuous Tests

#2 Get organized
– Conventions
– Naming

#3 Make Writing Tests Cheap
and easy
– Templates/snippets

#4 Prepare for changes
– Encapsulate constructors
– Automate object Creation
– Automate object comparison
Recommended read
• xUnit Test Patterns: Refactoring Test
Code by Gerard Meszaros
– http://xunitpatterns.com/

• Zero-Friction TDD by Mark Seemann
– http://blog.ploeh.dk/2009/01/28/ZeroFrictionTDD/
THANKS !
QUESTIONS ?
Thibaud DESODT
@tsimbalar

Contenu connexe

Tendances

C++ Testing Techniques Tips and Tricks - C++ London
C++ Testing Techniques Tips and Tricks - C++ LondonC++ Testing Techniques Tips and Tricks - C++ London
C++ Testing Techniques Tips and Tricks - C++ LondonClare Macrae
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnitkleinron
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleNoam Kfir
 
Testing – With Mock Objects
Testing – With Mock ObjectsTesting – With Mock Objects
Testing – With Mock Objectsemmettwalsh
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesTriTAUG
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildAndrei Sebastian Cîmpean
 
CBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxCBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxOrtus Solutions, Corp
 
2014 land your-first_patch_neutron
2014 land your-first_patch_neutron2014 land your-first_patch_neutron
2014 land your-first_patch_neutronRossella Sblendido
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 

Tendances (20)

C++ Testing Techniques Tips and Tricks - C++ London
C++ Testing Techniques Tips and Tricks - C++ LondonC++ Testing Techniques Tips and Tricks - C++ London
C++ Testing Techniques Tips and Tricks - C++ London
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Test box bdd
Test box bddTest box bdd
Test box bdd
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Testing – With Mock Objects
Testing – With Mock ObjectsTesting – With Mock Objects
Testing – With Mock Objects
 
May: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and ChallengesMay: Automated Developer Testing: Achievements and Challenges
May: Automated Developer Testing: Achievements and Challenges
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
CBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxCBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBox
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
2014 land your-first_patch_neutron
2014 land your-first_patch_neutron2014 land your-first_patch_neutron
2014 land your-first_patch_neutron
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 

Similaire à Unit tests = maintenance hell ?

Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
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
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentMeilan Ou
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.Bert Brouns
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsRody Middelkoop
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesTao Xie
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMSJustinHolt20
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовCOMAQA.BY
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
Property based testing - Less is more
Property based testing - Less is moreProperty based testing - Less is more
Property based testing - Less is moreHo Tien VU
 

Similaire à Unit tests = maintenance hell ? (20)

Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Skillwise Unit Testing
Skillwise Unit TestingSkillwise Unit Testing
Skillwise Unit Testing
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестов
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projects
 
Property based testing - Less is more
Property based testing - Less is moreProperty based testing - Less is more
Property based testing - Less is more
 

Dernier

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Dernier (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Unit tests = maintenance hell ?

  • 1. Unit Tests = Maintenance Hell ? Thibaud DESODT @tsimbalar
  • 2. This talk • About Unit-Testing – Why we do it – Why it can slow you down – How to ease the maintenance • Include : – .NET-based examples / tools – … can be applied to other platforms
  • 4. Value of Unit tests • Benefits Value of Unit tests – – – – – “toy” projects Avoid introducing bugs Executable documentation Regression detection Know when to stop Reduce fear / allow refactoring –… Unit-tests help build CONFIDENCE Codebase size
  • 5. But when the codebase grows …
  • 6. Quantity of Test Code • Prod Code vs Test Code Ratio – from 1:1 to 1:5 ! More Test Code than Prod Code ! • Muliplied efforts : – New Code – Changing existing code
  • 7. Lower Quality of Test Code • Viewed as less important than Prod Code – “Write Once” – Duplication / Copy+Paste – Less refactoring / improvements – Hard to read/understand • Technical Debt reduction has less priority
  • 8. Cost of Unit tests Cost of Unit Tests Unit-tests introduce FRICTION Codebase size
  • 9. Value vs Cost of Unit tests ROI WTF? Codebase size
  • 10. Unit Tests = Maintenance Hell ? It can be … but it does not have to !
  • 11. Value vs Cost of Unit tests ROI WTF? Codebase size
  • 12. Maintainability of codebase Solution 1 : give up on Unit Tests “Legacy Code is code without Tests” Michael Feathers Working Effectively with Legacy Code Codebase size
  • 13. WIN ! Value vs Cost of Unit tests Solution 2 : reduce the cost of test maintenance ! Codebase size
  • 15. TIP #1 : GET PROPER TOOLS
  • 16. Tools to manage thousands of tests – – – – Exploring tests / results Run All Run/Debug Current Test Run All Tests in current Test Class – Re-run last executed tests –… • VS2012 Test Explorer – Just kidding ! • Telerik JustCode • JetBrains ReSharper
  • 17. Continuous Testing • NCrunch ! – – – – Runs tests continuously Reports results without rebuilding or saving the files ! Impacted tests are run first Tests run in parallel • Expensive but worth it ! (159$/289$) – Give it a try http://www.ncrunch.net/ – Free alternative : http://continuoustests.com/
  • 18. TIP #2 : GET ORGANIZED
  • 19. Define conventions Convention Choice Test Projects [ProjectNamespace].Tests Test Classes One/class to test: [TestedClass]Test Test Methods [MethodName]_with_[Condition]_[ExpectedOutcome] Structure Arrange/Act/Assert or Given/When/Then Helper methods In Test Class (private static) In Test Project in namespace TestUtils In dedicated project « Test Support » Which convention you choose does not matter, as long as it’s used by everybody !
  • 20. Use « standard » variable names / prefixes • Common concepts : – sut (System Under Test) – actual (result of the action) – expected (expected value for the result) • Benefits : – Makes tests more homogenous – No need to think of it when writing the test – Resistant to class renaming !
  • 21. Typical structure [TestMethod] public void SomeMethod_with_SomeConditions_must_DoSomething() { // Arrange var sut = MakeSut(); var expected = "what it should return"; // Act var actual = sut.DoSomething(); // Assert Assert.AreEqual(expected, actual, "Should have done something"); }
  • 22. TIP #3 : MAKE WRITING TESTS CHEAP AND EASY !
  • 23. Use templates / snippets • Commonly created items : – Test Class – Test Methods – Test Helper Methods • … and share them with the team ! • Examples : – aaa, aae, any …
  • 24. TIP #4 : MAKE YOUR TESTS REFACTORING-FRIENDLY
  • 25. It will change ! “The only constant is change” Heraclitus of Ephesus 5th century BC • In 3 minutes / days / weeks … • Be ready !
  • 26. Constructors • Dependency Injection entry point – Changes when dependencies are added/removed – Impact in every test ! • Encapsulate it in a helper Method
  • 27. MakeSut() private static ClassToTest MakeSut( IDependency1 dep1 = null, IDependency2 dep2 = null) { dep1 = dep1 ?? new Mock<IDependency1>().Object; dep2 = dep2 ?? new Mock<IDependency2>().Object; return new ClassToTest(dep1, dep2); } – Default value for dependencies – Adding dependencies does not impact tests
  • 28. Test Data creation • Classes will change – New properties – Updated constructors …. • Automate generation of « auxiliary » test objects
  • 29. AutoFixture • Creates instances of classes var fixture = new Fixture(); var user = fixture.Create<User>(); – Populates constructor arguments – Populates properties – Recursive – Values derived from Property names > Install-Package AutoFixture https://github.com/AutoFixture/AutoFixture/wiki/Cheat-Sheet
  • 30. Test-specific comparison • Comparing objects is common – Actual vs expected – Should not override Equals() for the tests • Adding properties can break comparison
  • 31. Semantic Comparison var actualUser = new User(12, "john@rambo.com"); var expectedUser = new User(13, "tibo@desodt.com"); actualUser.AsSource().OfLikeness<User>().ShouldEqual(expectedUser); Ploeh.SemanticComparison.LikenessException: The provided value ProductionCode.Lib.Data.User did not match the expected value ProductionCode.Lib.Data.User. The following members did not match: - Id. - EmailAddress. actualUser.AsSource().OfLikeness<User>() .Without(u=> u.Id) .ShouldEqual(expectedUser); > Install-Package SemanticComparison
  • 33. Working with many Unit Tests • … is hard • Requires extra care – Up-front – During code maintenance • But pain can be reduced by: – Appropriate tools – Good habits TIPS #1 Proper Tools – Good Test Runner – Continuous Tests #2 Get organized – Conventions – Naming #3 Make Writing Tests Cheap and easy – Templates/snippets #4 Prepare for changes – Encapsulate constructors – Automate object Creation – Automate object comparison
  • 34. Recommended read • xUnit Test Patterns: Refactoring Test Code by Gerard Meszaros – http://xunitpatterns.com/ • Zero-Friction TDD by Mark Seemann – http://blog.ploeh.dk/2009/01/28/ZeroFrictionTDD/
  • 35. THANKS ! QUESTIONS ? Thibaud DESODT @tsimbalar

Notes de l'éditeur

  1. French software developer.NET web-apps for the French GovernmentAgile software team using Scrum … in BelgiumColleagues say I have some kind of obsession with Unit-Testing … they may be rightInterest in automated testing / unit-testing in particular 2-3 years agoI struggled a bit at the beginning, unit-testing + TDD in a legacy project. hard, but started to feel comfortable - adding = more fun and exciting. Triedto improve my skills, reading a lot about the topic and experimentingMy name is Thibaud DESODT , I am a French software developper, currently working in Belgium for the French government. I work in a small Scrum team on the development of .NET-based web applications. According to my colleagues, I have some kind of obsession about unit tests ... the truth is they may be right .... I started to get interested in automated testing and in unit-testing in particular 2-3 years ago. As most of us did, I struggled a bit at the beginning, trying to apply unit-testing and TDD to the current legacy project. It was hard, but I soon started to feel more comfortable and it made adding features to the system a bit more fun and exciting. Since then, I&apos;ve tried to improve my skills, reading a lot about the topic, and trying new things in the projects I work on.
  2. Enough about meIt’s not about : Integration Testing, Manual Testing, TDD … When it feels like they are slowing you down … how to reduce that feeling and get more productive on codebases with lots of unit-testsTargets people with previous knowledge of Unit-testingenough about me .... this talk is about Unit-Testing (not integration testing, not manual testing ...) ... when it starts to feel like they are slowing you down, and how to avoid or at least reduce that feeling. I&apos;ll talk a bit about unit-testing in general and then I&apos;ll try to provide tips to improve test maintenance. Because I am a .NET developer, most of the code and tools I&apos;m going to show are related to the .NET ecostystem, but I guess most of the ideas can apply to other development platform ... (oh and yes, there won&apos;t be any VB.NET , sorry ;) ).
  3. Shorter Feedback loops require more automationMore automation requires more confidence
  4. With small projects, Unit Tests don’t provide so much valueBut as soon as the codebase grows, you need confidence to move forward … and Unit Test’s value gets bigger
  5. Problems with unit tests over time : All those unit tests may slow us downit can feel like we struggle / they slow us down ...mostly because it&apos;s more code to maintain ! some kind of duplication
  6. there are lots because they are the most granular part and least fragile ! (test pyramid)Just the number makes it hard to manage and have a good view of all the unit tests in the project
  7. usually more Loc than production code 1:1 to 1:5 !Each line of code in prod means at least 2 lines of code to maintain
  8. Writing tests is actually expensive !
  9. Writing tests is actually expensive !
  10. Let&apos;s review some best/worst practices to see WHAT TO DO and WHAT NOT TO DO when working with code bases with lots of unit tests .... in some random order ... some very specific and technical, some more general
  11. Once you reach several hundred/thousands unit tests, you need good tools to manage / run your tests.Does anybody use the default Visual Studio Test Runner ? do you like it ?ReSharper Test-runner ! . or others (CodeRush ? Driven ? )You want to be able to : - run current test- run tests in current test class- run tests in current namespace- run tests in current project- run ALL tests+ re-run last run
  12. Bonus : do not forget to run unit tests !Best way = run them constantly NCrunch ! show how it works(alternative : MightyMoose ?)
  13. Let&apos;s review some best/worst practices to see WHAT TO DO and WHAT NOT TO DO when working with code bases with lots of unit tests .... in some random order ... some very specific and technical, some more general
  14. It’s hard to maintain an unheterogenous Test Code Base !It’s hard to findwhatyour are looking forIt’s hard to add tests in it
  15. Quick demo des Snippets
  16. Who uses dependency injection ?UserNotificationServicewhichsends an email to a user …Wewantit to alsosend an SMS-&gt; introduce a new constructor argument
  17. Ajout d’un paramètre PhoneNumber sur User … impact sur les tests alors que la valeur a peu d’importance
  18. Envoi du SMS … si on ajoute une propriété à SMS que devient la comparaison ?