SlideShare a Scribd company logo
1 of 31
Practical Unit Testing in C & C++
Agile At Scale
by Matt Hargett
<plaztiksyke@gmail.com>
Summary
• The only reason to do unit testing is for
sustainable, competitive business advantage
• Unit testing is the most reliable route to a
modular/OO design, in my experience
• Unit testing is best used in conjunction with
automated integration and system testing
• Focusing on ease of consumption and
maintenance of unit tests is key
– C/C++ is not a valid excuse for messy syntax
Agenda
• What unit testing is/is not
• Simple (but reality-derived) Unit Test in C
• Breaking dependencies
– Compile time
– Link time
– Preprocessor time

• Writing unit tests to be read
• Mocking
– Link time
– Runtime

• Performance
What unit testing is
• Worth mentioning, because the concept has
gotten fuzzier over time
– “a method by which individual units of source code
are tested to determine if they are fit for use”

• Modularity is a requirement for real unit tests
– “the degree to which a system’s components may be
separated and recombined”
– Separating interface from implementation

• Testing things that could possibly break
• Fast feedback that you can get while coding
What unit testing is not
• Producing a test binary that can only run in a
special environment (modulo native asm)
• Tests that run in developer environment, but
link against the entire system
• An excuse to treat test code differently
– Keep duplication low

• An excuse to roll your own framework
• An academic distraction of exercising all inputs
Types of developer testing
test

Unit

K

C1

C3

Integration

C2

C4

C5

System
Scaling: How to start developer testing
• Start small
– One pair writing tests with specific goal

• Focus on real bugs that already happened
– Write tests that would have failed for last 3 bugs

• High quality from inception
– Low duplication, sensible file management

• Accessible
– Anyone can build and run after fresh checkout

• Split the pair and continue
Simple Unit Test in C: Start with a Bug
• Bug report says there’s a crash when the
device is missing
• How do we test regardless of the hardware?
broadcast.c
Simple Unit Test in C: Stub collaborators
• Write a test program to reproduce the crash
broadcast_test.c

• Compile only the test and the module
• Satisfy the undefined references with stubs
mock_pci.c
Simple Unit Test: Running
• We expect a crash!

• How do we know it’s the “right” crash?
• What if we need to stub different values?
• We need something smarter than stubs
– Mocks
Simple Unit Test: Mocking
• We need to have different return values each
time the mock is called
• On a per-function (or per-instance) scope
• So we can exercise robust code paths
• Without too much maintenance overhead
• With the specification in the test’s scope
Simple Unit Test: Mocking Example
• Now we don’t need to look in stub files

• And we can prove details of a fix

• If ‘printk’ function isn’t called, test will fail
Scaling: Optimize for readability
• Tests are executable documentation
• They will be read many more times than they are
written
• Favor fluent syntax that reads left-to-right
• Passing tests should have very little output
– Even under valgrind, AddressSanitizer, etc

• Failing tests should provide good clues to avoid
context switches to debugger/editor
• Tests and Mocks for a given component should be
easy to find, “near” original source file
Readability Example: cgreen
• http://cgreen.sf.net
• Cross-language C/C++
• No weird code generators – pure C/C++
Mocking: Link time
• Cgreen also supplies a mock framework
Mocking: Runtime
• Function pointers
• C++ interfaces
– Mockitopp!
Breaking Dependencies
• Necessary to mock/stub collaborators
• Mocking collaborators reduces surface area to
read/debug when a test fails
• Introducing seams increases modularity
• Which can make it easier to add features, do
rapid experiments, and generally innovate
Breaking Dependencies: Compile Time
• Problem: Collaborating functions are defined
in a header file
• Solution: Move them into a source file for linktime substitutability
• Solution: Create a mock header file and put its
path on the front of your unit test compile
Breaking Dependencies: Move body
• Move target function/method bodies from
header files to source files
– Make a new file and add to build, if need be
– Speeds up compile, can reduce transitive includes
– Keeps interface and implementation separate

• What about inline functions?
• What about template functions?
Move Body: Template functions

• Sometimes templates are implicit interfaces
• Or, Extract problematic part to separate class
Mock header
• A third-party header contains a non-trivial
collaborating class/function
• mkdir ~/src/mock_include
• cp ~/src/include/trouble.h
• Gut the trouble.h copy of implementation
detail, leaving only declarations
• Put –Imock_include on the front of your unit
test build command
Breaking Dependencies: Link time
• Link only against the object files your unit test
needs
– The link errors will tell you what to do
– Aggressively mock non-trivial collaborators

• If transitive dependencies starts to balloon
– Aggressively mock non-trivial collaborators

• What about static ctors?
Breaking Dependencies: Preprocessor
• Problem: A third-party header calls a nontrivial collaborating function
• Solution: Override non-trivial function calls by
defining the symbols in your unit test build
Breaking Dependencies: Redefine symbols
• Redefine the symbol on the unit test build
commandline
– -Dtroublesome_func=mock_troublesome_func

• Then supply a link-time mock
Breaking Dependencies: Static class
• Problem: static class makes mocking irritating
• Solution:
– Make the static methods instance methods
– Extract a pure virtual base class for methods
– Make original class a singleton that returns pure
virtual base class
– Update callers
• %s/Class::MethodName/Class::instance()->MethodName/g
Breaking Dependencies: Static -> Singleton
Performance in the Code
• PROVE IT WITH A PROFILER OR BENCHMARK
• Improving modularity/testability doesn’t have to mean
decreased performance
– Link Time Optimization
• Optimizes across object file boundaries

– De-virtualization
• Tracks concrete types/function pointers and optimizes across type
boundaries

– Profile Guided Optimization
• Can easily get back your loss, driven by automated acceptance tests

– Optimize for your architecture!
• -march=native

• If you are serious about performance, get compiler support
– KugelWorks, EmbeCosm, etc
Performance in the Team
• Tests provide
– Executable documentation
– Safety nets for moving fast

• The ability to scale
– To larger (or smaller) teams
– To more customers
– To competitive markets

• To create and maintain a predictable pace
Scalability: Summary
•
•
•
•

Start small, focus on creating repeatable value
Store test and mock artifacts near sources
Run fast tests with a single build command
Measure code coverage, fail build if it falls below agreedupon value
• Tests need to meet same code metric standards as
implementation code
– pmccabe, copy-paste detector (CPD), etc
– Fail build if thresholds are exceeded

• Constantly reduce build and test times while increasing
coverage
– Maximize the economy of % coverage per second
Links
• Cgreen
– http://cgreen.sf.net

• Mockitopp
– http://code.google.com/p/mockitopp/
• Highly recommend tracking their repositories and
building from source in your build

• Toolchain support/enhancement vendors
– http://kugelworks.com
– http://embecosm.com/
Thanks!
Questions?
Music: http://themakingofthemakingof.com
Music also on iTunes, Amazon, Google Play, Spotify
Twitter: @syke
Email: plaztiksyke@gmail.com
Next Talk C++ Asynchronous I/O
by Michael Caisse:10:45 AM Sunday Room: 8338

More Related Content

What's hot

Usr for pcr machine
Usr for pcr machineUsr for pcr machine
Usr for pcr machineAnwar Parvez
 
Test Case Design
Test Case DesignTest Case Design
Test Case Designacatalin
 
Herramientas para la automatización de pruebas en el proceso de certificación...
Herramientas para la automatización de pruebas en el proceso de certificación...Herramientas para la automatización de pruebas en el proceso de certificación...
Herramientas para la automatización de pruebas en el proceso de certificación...CristopherVega14
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview QA InfoTech
 
Boost your App with Gatling
Boost your App with GatlingBoost your App with Gatling
Boost your App with GatlingKnoldus Inc.
 
Types of software testing
Types of software testingTypes of software testing
Types of software testingTestbytes
 
Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Atul Pant
 
Testing check list
Testing check listTesting check list
Testing check listAtul Pant
 
Code Quality Lightning Talk
Code Quality Lightning TalkCode Quality Lightning Talk
Code Quality Lightning TalkJonathan Gregory
 
Install jenkins and sonar qube integration
Install jenkins and sonar qube integrationInstall jenkins and sonar qube integration
Install jenkins and sonar qube integrationAnkit Kumar
 
Unit Testing vs Integration Testing
Unit Testing vs Integration TestingUnit Testing vs Integration Testing
Unit Testing vs Integration TestingRock Interview
 
Software Testing Basic Concepts
Software Testing Basic ConceptsSoftware Testing Basic Concepts
Software Testing Basic Conceptswesovi
 
Migrating from PDE to Tycho builds
Migrating from PDE to Tycho buildsMigrating from PDE to Tycho builds
Migrating from PDE to Tycho buildsTeodor Madan
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testingHadi Fadlallah
 
Software testing tools (free and open source)
Software testing tools (free and open source)Software testing tools (free and open source)
Software testing tools (free and open source)Wael Mansour
 

What's hot (20)

Usr for pcr machine
Usr for pcr machineUsr for pcr machine
Usr for pcr machine
 
Test Case Design
Test Case DesignTest Case Design
Test Case Design
 
Herramientas para la automatización de pruebas en el proceso de certificación...
Herramientas para la automatización de pruebas en el proceso de certificación...Herramientas para la automatización de pruebas en el proceso de certificación...
Herramientas para la automatización de pruebas en el proceso de certificación...
 
Sonar
SonarSonar
Sonar
 
Code coverage
Code coverageCode coverage
Code coverage
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview
 
Code Coverage
Code CoverageCode Coverage
Code Coverage
 
Boost your App with Gatling
Boost your App with GatlingBoost your App with Gatling
Boost your App with Gatling
 
Types of software testing
Types of software testingTypes of software testing
Types of software testing
 
Performance Test Plan - Sample 1
Performance Test Plan - Sample 1Performance Test Plan - Sample 1
Performance Test Plan - Sample 1
 
Testing check list
Testing check listTesting check list
Testing check list
 
Code Quality Lightning Talk
Code Quality Lightning TalkCode Quality Lightning Talk
Code Quality Lightning Talk
 
Software testing Report
Software testing ReportSoftware testing Report
Software testing Report
 
Install jenkins and sonar qube integration
Install jenkins and sonar qube integrationInstall jenkins and sonar qube integration
Install jenkins and sonar qube integration
 
Unit Testing vs Integration Testing
Unit Testing vs Integration TestingUnit Testing vs Integration Testing
Unit Testing vs Integration Testing
 
Software Testing Basic Concepts
Software Testing Basic ConceptsSoftware Testing Basic Concepts
Software Testing Basic Concepts
 
Migrating from PDE to Tycho builds
Migrating from PDE to Tycho buildsMigrating from PDE to Tycho builds
Migrating from PDE to Tycho builds
 
Introduction to software testing
Introduction to software testingIntroduction to software testing
Introduction to software testing
 
Software_Testing_ppt.pptx
Software_Testing_ppt.pptxSoftware_Testing_ppt.pptx
Software_Testing_ppt.pptx
 
Software testing tools (free and open source)
Software testing tools (free and open source)Software testing tools (free and open source)
Software testing tools (free and open source)
 

Viewers also liked

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Software Engineering Fundamentals
Software Engineering FundamentalsSoftware Engineering Fundamentals
Software Engineering FundamentalsRahul Sudame
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Test driven development in C
Test driven development in CTest driven development in C
Test driven development in CAmritayan Nayak
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleBenjamin Eberlei
 
Software testing.ppt
Software testing.pptSoftware testing.ppt
Software testing.pptKomal Garg
 
Практика использования Dependency Injection
Практика использования Dependency InjectionПрактика использования Dependency Injection
Практика использования Dependency InjectionPlatonov Sergey
 
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Platonov Sergey
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыPlatonov Sergey
 
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
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Googleyaevents
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeTerry Yin
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioSergey Platonov
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkHumberto Marchezi
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
Как писать красивый код или основы SOLID
Как писать красивый код или основы SOLIDКак писать красивый код или основы SOLID
Как писать красивый код или основы SOLIDPavel Tsukanov
 
[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
 

Viewers also liked (20)

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Software Engineering Fundamentals
Software Engineering FundamentalsSoftware Engineering Fundamentals
Software Engineering Fundamentals
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Test driven development in C
Test driven development in CTest driven development in C
Test driven development in C
 
Modern c++
Modern c++Modern c++
Modern c++
 
Bijender (1)
Bijender (1)Bijender (1)
Bijender (1)
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by Example
 
Software testing.ppt
Software testing.pptSoftware testing.ppt
Software testing.ppt
 
Практика использования Dependency Injection
Практика использования Dependency InjectionПрактика использования Dependency Injection
Практика использования Dependency Injection
 
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Василий Сорокин, “Google C++ Mocking and Test Frameworks”
Василий Сорокин, “Google C++ Mocking and Test Frameworks”
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в 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 driven development and unit testing with examples in C++
 
Юнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, GoogleЮнит-тестирование и Google Mock. Влад Лосев, Google
Юнит-тестирование и Google Mock. Влад Лосев, Google
 
Adding Unit Test To Legacy Code
Adding Unit Test To Legacy CodeAdding Unit Test To Legacy Code
Adding Unit Test To Legacy Code
 
Павел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.ioПавел Филонов, Разделяй и управляй вместе с Conan.io
Павел Филонов, Разделяй и управляй вместе с Conan.io
 
C++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing FrameworkC++ Unit Test with Google Testing Framework
C++ Unit Test with Google Testing Framework
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Как писать красивый код или основы SOLID
Как писать красивый код или основы SOLIDКак писать красивый код или основы SOLID
Как писать красивый код или основы SOLID
 
[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
 

Similar to Practical unit testing in c & c++

TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)Peter Kofler
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approachEnrico Da Ros
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspecjeffrey1ross
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Ortus Solutions, Corp
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Uma Ghotikar
 
Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Red Gate Software
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовCOMAQA.BY
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
An Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewAn Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewBlue Elephant Consulting
 
QA Team Goes to Agile and Continuous integration
QA Team Goes to Agile and Continuous integrationQA Team Goes to Agile and Continuous integration
QA Team Goes to Agile and Continuous integrationSujit Ghosh
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting examplecorehard_by
 
Small is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case DesignSmall is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case DesignGeorgina Tilby
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CDShanmuga S Muthu
 
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
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
Architecting for the cloud storage build test
Architecting for the cloud storage build testArchitecting for the cloud storage build test
Architecting for the cloud storage build testLen Bass
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham.NET Conf UY
 

Similar to Practical unit testing in c & c++ (20)

TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)TDD and Related Techniques for Non Developers (2012)
TDD and Related Techniques for Non Developers (2012)
 
Testing, a pragmatic approach
Testing, a pragmatic approachTesting, a pragmatic approach
Testing, a pragmatic approach
 
Beginners overview of automated testing with Rspec
Beginners overview of automated testing with RspecBeginners overview of automated testing with Rspec
Beginners overview of automated testing with Rspec
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014Get Testing with tSQLt - SQL In The City Workshop 2014
Get Testing with tSQLt - SQL In The City Workshop 2014
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестов
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
An Introduction To Software Development - Final Review
An Introduction To Software Development - Final ReviewAn Introduction To Software Development - Final Review
An Introduction To Software Development - Final Review
 
QA Team Goes to Agile and Continuous integration
QA Team Goes to Agile and Continuous integrationQA Team Goes to Agile and Continuous integration
QA Team Goes to Agile and Continuous integration
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting example
 
Small is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case DesignSmall is Beautiful- Fully Automate your Test Case Design
Small is Beautiful- Fully Automate your Test Case Design
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CD
 
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
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
CNUG TDD June 2014
CNUG TDD June 2014CNUG TDD June 2014
CNUG TDD June 2014
 
Architecting for the cloud storage build test
Architecting for the cloud storage build testArchitecting for the cloud storage build test
Architecting for the cloud storage build test
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 

Recently uploaded

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

Practical unit testing in c & c++

  • 1. Practical Unit Testing in C & C++ Agile At Scale by Matt Hargett <plaztiksyke@gmail.com>
  • 2. Summary • The only reason to do unit testing is for sustainable, competitive business advantage • Unit testing is the most reliable route to a modular/OO design, in my experience • Unit testing is best used in conjunction with automated integration and system testing • Focusing on ease of consumption and maintenance of unit tests is key – C/C++ is not a valid excuse for messy syntax
  • 3. Agenda • What unit testing is/is not • Simple (but reality-derived) Unit Test in C • Breaking dependencies – Compile time – Link time – Preprocessor time • Writing unit tests to be read • Mocking – Link time – Runtime • Performance
  • 4. What unit testing is • Worth mentioning, because the concept has gotten fuzzier over time – “a method by which individual units of source code are tested to determine if they are fit for use” • Modularity is a requirement for real unit tests – “the degree to which a system’s components may be separated and recombined” – Separating interface from implementation • Testing things that could possibly break • Fast feedback that you can get while coding
  • 5. What unit testing is not • Producing a test binary that can only run in a special environment (modulo native asm) • Tests that run in developer environment, but link against the entire system • An excuse to treat test code differently – Keep duplication low • An excuse to roll your own framework • An academic distraction of exercising all inputs
  • 6. Types of developer testing test Unit K C1 C3 Integration C2 C4 C5 System
  • 7. Scaling: How to start developer testing • Start small – One pair writing tests with specific goal • Focus on real bugs that already happened – Write tests that would have failed for last 3 bugs • High quality from inception – Low duplication, sensible file management • Accessible – Anyone can build and run after fresh checkout • Split the pair and continue
  • 8. Simple Unit Test in C: Start with a Bug • Bug report says there’s a crash when the device is missing • How do we test regardless of the hardware? broadcast.c
  • 9. Simple Unit Test in C: Stub collaborators • Write a test program to reproduce the crash broadcast_test.c • Compile only the test and the module • Satisfy the undefined references with stubs mock_pci.c
  • 10. Simple Unit Test: Running • We expect a crash! • How do we know it’s the “right” crash? • What if we need to stub different values? • We need something smarter than stubs – Mocks
  • 11. Simple Unit Test: Mocking • We need to have different return values each time the mock is called • On a per-function (or per-instance) scope • So we can exercise robust code paths • Without too much maintenance overhead • With the specification in the test’s scope
  • 12. Simple Unit Test: Mocking Example • Now we don’t need to look in stub files • And we can prove details of a fix • If ‘printk’ function isn’t called, test will fail
  • 13. Scaling: Optimize for readability • Tests are executable documentation • They will be read many more times than they are written • Favor fluent syntax that reads left-to-right • Passing tests should have very little output – Even under valgrind, AddressSanitizer, etc • Failing tests should provide good clues to avoid context switches to debugger/editor • Tests and Mocks for a given component should be easy to find, “near” original source file
  • 14. Readability Example: cgreen • http://cgreen.sf.net • Cross-language C/C++ • No weird code generators – pure C/C++
  • 15. Mocking: Link time • Cgreen also supplies a mock framework
  • 16. Mocking: Runtime • Function pointers • C++ interfaces – Mockitopp!
  • 17. Breaking Dependencies • Necessary to mock/stub collaborators • Mocking collaborators reduces surface area to read/debug when a test fails • Introducing seams increases modularity • Which can make it easier to add features, do rapid experiments, and generally innovate
  • 18. Breaking Dependencies: Compile Time • Problem: Collaborating functions are defined in a header file • Solution: Move them into a source file for linktime substitutability • Solution: Create a mock header file and put its path on the front of your unit test compile
  • 19. Breaking Dependencies: Move body • Move target function/method bodies from header files to source files – Make a new file and add to build, if need be – Speeds up compile, can reduce transitive includes – Keeps interface and implementation separate • What about inline functions? • What about template functions?
  • 20. Move Body: Template functions • Sometimes templates are implicit interfaces • Or, Extract problematic part to separate class
  • 21. Mock header • A third-party header contains a non-trivial collaborating class/function • mkdir ~/src/mock_include • cp ~/src/include/trouble.h • Gut the trouble.h copy of implementation detail, leaving only declarations • Put –Imock_include on the front of your unit test build command
  • 22. Breaking Dependencies: Link time • Link only against the object files your unit test needs – The link errors will tell you what to do – Aggressively mock non-trivial collaborators • If transitive dependencies starts to balloon – Aggressively mock non-trivial collaborators • What about static ctors?
  • 23. Breaking Dependencies: Preprocessor • Problem: A third-party header calls a nontrivial collaborating function • Solution: Override non-trivial function calls by defining the symbols in your unit test build
  • 24. Breaking Dependencies: Redefine symbols • Redefine the symbol on the unit test build commandline – -Dtroublesome_func=mock_troublesome_func • Then supply a link-time mock
  • 25. Breaking Dependencies: Static class • Problem: static class makes mocking irritating • Solution: – Make the static methods instance methods – Extract a pure virtual base class for methods – Make original class a singleton that returns pure virtual base class – Update callers • %s/Class::MethodName/Class::instance()->MethodName/g
  • 27. Performance in the Code • PROVE IT WITH A PROFILER OR BENCHMARK • Improving modularity/testability doesn’t have to mean decreased performance – Link Time Optimization • Optimizes across object file boundaries – De-virtualization • Tracks concrete types/function pointers and optimizes across type boundaries – Profile Guided Optimization • Can easily get back your loss, driven by automated acceptance tests – Optimize for your architecture! • -march=native • If you are serious about performance, get compiler support – KugelWorks, EmbeCosm, etc
  • 28. Performance in the Team • Tests provide – Executable documentation – Safety nets for moving fast • The ability to scale – To larger (or smaller) teams – To more customers – To competitive markets • To create and maintain a predictable pace
  • 29. Scalability: Summary • • • • Start small, focus on creating repeatable value Store test and mock artifacts near sources Run fast tests with a single build command Measure code coverage, fail build if it falls below agreedupon value • Tests need to meet same code metric standards as implementation code – pmccabe, copy-paste detector (CPD), etc – Fail build if thresholds are exceeded • Constantly reduce build and test times while increasing coverage – Maximize the economy of % coverage per second
  • 30. Links • Cgreen – http://cgreen.sf.net • Mockitopp – http://code.google.com/p/mockitopp/ • Highly recommend tracking their repositories and building from source in your build • Toolchain support/enhancement vendors – http://kugelworks.com – http://embecosm.com/
  • 31. Thanks! Questions? Music: http://themakingofthemakingof.com Music also on iTunes, Amazon, Google Play, Spotify Twitter: @syke Email: plaztiksyke@gmail.com Next Talk C++ Asynchronous I/O by Michael Caisse:10:45 AM Sunday Room: 8338