SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Test Process
Test ProcessTest Process
Test Processtokarthik
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Bug reporting and tracking
Bug reporting and trackingBug reporting and tracking
Bug reporting and trackingVadym Muliavka
 
ISTQB - What's testing
ISTQB - What's testingISTQB - What's testing
ISTQB - What's testingHoangThiHien1
 
Basic software-testing-concepts
Basic software-testing-conceptsBasic software-testing-concepts
Basic software-testing-conceptsmedsherb
 
Test Management introduction
Test Management introductionTest Management introduction
Test Management introductionOana Feidi
 
Test Automation Strategies For Agile
Test Automation Strategies For AgileTest Automation Strategies For Agile
Test Automation Strategies For AgileNaresh Jain
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
What is Integration Testing? | Edureka
What is Integration Testing? | EdurekaWhat is Integration Testing? | Edureka
What is Integration Testing? | EdurekaEdureka!
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and typesConfiz
 
Agile QA presentation
Agile QA presentationAgile QA presentation
Agile QA presentationCarl Bruiners
 
테스트자동화 성공전략
테스트자동화 성공전략테스트자동화 성공전략
테스트자동화 성공전략SangIn Choung
 

Tendances (20)

Test Process
Test ProcessTest Process
Test Process
 
API testing - Japura.pptx
API testing - Japura.pptxAPI testing - Japura.pptx
API testing - Japura.pptx
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit testing
Unit testing Unit testing
Unit testing
 
Bug reporting and tracking
Bug reporting and trackingBug reporting and tracking
Bug reporting and tracking
 
ISTQB - What's testing
ISTQB - What's testingISTQB - What's testing
ISTQB - What's testing
 
Basic software-testing-concepts
Basic software-testing-conceptsBasic software-testing-concepts
Basic software-testing-concepts
 
Test Management introduction
Test Management introductionTest Management introduction
Test Management introduction
 
ISTQB foundation level - day 2
ISTQB foundation level - day 2ISTQB foundation level - day 2
ISTQB foundation level - day 2
 
Test Automation Strategies For Agile
Test Automation Strategies For AgileTest Automation Strategies For Agile
Test Automation Strategies For Agile
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Software testing
Software testingSoftware testing
Software testing
 
Testing & Quality Assurance
Testing & Quality AssuranceTesting & Quality Assurance
Testing & Quality Assurance
 
What is Integration Testing? | Edureka
What is Integration Testing? | EdurekaWhat is Integration Testing? | Edureka
What is Integration Testing? | Edureka
 
Test Automation
Test AutomationTest Automation
Test Automation
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and types
 
Agile QA presentation
Agile QA presentationAgile QA presentation
Agile QA presentation
 
테스트자동화 성공전략
테스트자동화 성공전략테스트자동화 성공전략
테스트자동화 성공전략
 
Unit testing
Unit testingUnit testing
Unit testing
 

En vedette

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Software Engineering Fundamentals
Software Engineering FundamentalsSoftware Engineering Fundamentals
Software Engineering FundamentalsRahul Sudame
 
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
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test frameworkAbner Chih Yi Huang
 

En vedette (20)

UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Software Engineering Fundamentals
Software Engineering FundamentalsSoftware Engineering Fundamentals
Software Engineering Fundamentals
 
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
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 

Similaire à 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
 

Similaire à 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
 

Dernier

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Dernier (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

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