SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Clare Macrae
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
kleinron
 
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 Automation
Stephen Fuqua
 
Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016Functional Tests. PHP Unconf 2016
Functional Tests. PHP Unconf 2016
Vladislav Fedorischev
 
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
Noam Kfir
 
Testing – With Mock Objects
Testing – With Mock ObjectsTesting – With Mock Objects
Testing – With Mock Objects
emmettwalsh
 
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
TriTAUG
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
Arvind Vyas
 
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
Andrei 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 TestBox
Ortus Solutions, Corp
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
Anuar Nurmakanov
 
2014 land your-first_patch_neutron
2014 land your-first_patch_neutron2014 land your-first_patch_neutron
2014 land your-first_patch_neutron
Rossella 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 Mock
ICS
 
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 Research
Vasil Remeniuk
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Scott Leberknight
 

What's hot (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
 

Similar to 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
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
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
 
Skillwise Unit Testing
Skillwise Unit TestingSkillwise Unit Testing
Skillwise Unit Testing
Skillwise Group
 
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 Training
Ram 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 8
Jay 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
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
Mayank Srivastava
 
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
Rody Middelkoop
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
Tao 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 .NET
Baskar K
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Testing in Craft CMS
Testing in Craft CMSTesting in Craft CMS
Testing in Craft CMS
JustinHolt20
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Sergey Aganezov
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
David 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 projects
Vincent Massol
 
Property based testing - Less is more
Property based testing - Less is moreProperty based testing - Less is more
Property based testing - Less is more
Ho Tien VU
 

Similar to 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
 

Recently uploaded

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 

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

Editor's Notes

  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 ?