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

PDF
Into The Box 2018 | Assert control over your legacy applications
PDF
How and what to unit test
PPTX
Principles and patterns for test driven development
PDF
An Introduction to Unit Test Using NUnit
PDF
Unit Test + Functional Programming = Love
PPTX
NUnit Features Presentation
PPTX
Testing 101
Into The Box 2018 | Assert control over your legacy applications
How and what to unit test
Principles and patterns for test driven development
An Introduction to Unit Test Using NUnit
Unit Test + Functional Programming = Love
NUnit Features Presentation
Testing 101

What's hot (20)

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

Similar to Unit tests = maintenance hell ? (20)

PPTX
Test in action – week 1
PPTX
Unit tests and TDD
PDF
An Introduction to Test Driven Development
PPTX
Skillwise Unit Testing
PPTX
Test-Driven Development
PPTX
Unit Testng with PHP Unit - A Step by Step Training
PDF
I am afraid of no test! The power of BDD
PPTX
Automated php unit testing in drupal 8
PPTX
VT.NET 20160411: An Intro to Test Driven Development (TDD)
PPTX
Techorama 2017 - Testing the unit, and beyond.
PDF
CNUG TDD June 2014
PPTX
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
PDF
Automated Developer Testing: Achievements and Challenges
ODP
Beginners - Get Started With Unit Testing in .NET
PDF
An introduction to unit testing
PPTX
presentation des google test dans un contexte de tdd
PDF
Testing in Craft CMS
PPTX
Test Driven Development
PDF
Test Driven Development with Sql Server
PPTX
Системный взгляд на параллельный запуск Selenium тестов
Test in action – week 1
Unit tests and TDD
An Introduction to Test Driven Development
Skillwise Unit Testing
Test-Driven Development
Unit Testng with PHP Unit - A Step by Step Training
I am afraid of no test! The power of BDD
Automated php unit testing in drupal 8
VT.NET 20160411: An Intro to Test Driven Development (TDD)
Techorama 2017 - Testing the unit, and beyond.
CNUG TDD June 2014
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Automated Developer Testing: Achievements and Challenges
Beginners - Get Started With Unit Testing in .NET
An introduction to unit testing
presentation des google test dans un contexte de tdd
Testing in Craft CMS
Test Driven Development
Test Driven Development with Sql Server
Системный взгляд на параллельный запуск Selenium тестов
Ad

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
KodekX | Application Modernization Development
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Modernizing your data center with Dell and AMD
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
A Presentation on Artificial Intelligence
PDF
Approach and Philosophy of On baking technology
DOCX
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MYSQL Presentation for SQL database connectivity
KodekX | Application Modernization Development
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Encapsulation_ Review paper, used for researhc scholars
Modernizing your data center with Dell and AMD
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
Understanding_Digital_Forensics_Presentation.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
A Presentation on Artificial Intelligence
Approach and Philosophy of On baking technology
The AUB Centre for AI in Media Proposal.docx

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

  • #3: 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.
  • #4: 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 ;) ).
  • #6: Shorter Feedback loops require more automationMore automation requires more confidence
  • #8: 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
  • #9: 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
  • #10: 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
  • #11: 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
  • #14: Writing tests is actually expensive !
  • #16: Writing tests is actually expensive !
  • #20: 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
  • #21: 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
  • #22: Bonus : do not forget to run unit tests !Best way = run them constantly NCrunch ! show how it works(alternative : MightyMoose ?)
  • #23: 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
  • #24: 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
  • #29: Quick demo des Snippets
  • #32: Who uses dependency injection ?UserNotificationServicewhichsends an email to a user …Wewantit to alsosend an SMS-&gt; introduce a new constructor argument
  • #34: Ajout d’un paramètre PhoneNumber sur User … impact sur les tests alors que la valeur a peu d’importance
  • #36: Envoi du SMS … si on ajoute une propriété à SMS que devient la comparaison ?