SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

GitOps is IaC done right
GitOps is IaC done rightGitOps is IaC done right
GitOps is IaC done rightChen Cheng-Wei
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework IntroductionPekka Klärck
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Se (techniques for black box testing ppt)
Se (techniques for black box testing ppt)Se (techniques for black box testing ppt)
Se (techniques for black box testing ppt)Mani Kanth
 
White Box Testing
White Box TestingWhite Box Testing
White Box TestingAlisha Roy
 
Risk based testing and random testing
Risk based testing and random testingRisk based testing and random testing
Risk based testing and random testingHimanshu
 
Improving Automated Tests with Fluent Assertions
Improving Automated Tests with Fluent Assertions Improving Automated Tests with Fluent Assertions
Improving Automated Tests with Fluent Assertions TestingCR
 
Session 8 assertion_based_verification_and_interfaces
Session 8 assertion_based_verification_and_interfacesSession 8 assertion_based_verification_and_interfaces
Session 8 assertion_based_verification_and_interfacesNirav Desai
 
UVM ARCHITECTURE FOR VERIFICATION
UVM ARCHITECTURE FOR VERIFICATIONUVM ARCHITECTURE FOR VERIFICATION
UVM ARCHITECTURE FOR VERIFICATIONIAEME Publication
 
SystemVerilog based OVM and UVM Verification Methodologies
SystemVerilog based OVM and UVM Verification MethodologiesSystemVerilog based OVM and UVM Verification Methodologies
SystemVerilog based OVM and UVM Verification MethodologiesRamdas Mozhikunnath
 
5 black box and grey box testing
5   black box and grey box testing5   black box and grey box testing
5 black box and grey box testingYisal Khan
 
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus Introduction to DevOps. Continuous Integration by Myroslav Dmytrus
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus Binary Studio
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdfNigussMehari4
 
Dynamic Testing
Dynamic TestingDynamic Testing
Dynamic TestingJimi Patel
 

Mais procurados (20)

GitOps is IaC done right
GitOps is IaC done rightGitOps is IaC done right
GitOps is IaC done right
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Se (techniques for black box testing ppt)
Se (techniques for black box testing ppt)Se (techniques for black box testing ppt)
Se (techniques for black box testing ppt)
 
White Box Testing
White Box TestingWhite Box Testing
White Box Testing
 
Risk based testing and random testing
Risk based testing and random testingRisk based testing and random testing
Risk based testing and random testing
 
Improving Automated Tests with Fluent Assertions
Improving Automated Tests with Fluent Assertions Improving Automated Tests with Fluent Assertions
Improving Automated Tests with Fluent Assertions
 
Advance Peripheral Bus
Advance Peripheral Bus Advance Peripheral Bus
Advance Peripheral Bus
 
Session 8 assertion_based_verification_and_interfaces
Session 8 assertion_based_verification_and_interfacesSession 8 assertion_based_verification_and_interfaces
Session 8 assertion_based_verification_and_interfaces
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 
UVM ARCHITECTURE FOR VERIFICATION
UVM ARCHITECTURE FOR VERIFICATIONUVM ARCHITECTURE FOR VERIFICATION
UVM ARCHITECTURE FOR VERIFICATION
 
SystemVerilog based OVM and UVM Verification Methodologies
SystemVerilog based OVM and UVM Verification MethodologiesSystemVerilog based OVM and UVM Verification Methodologies
SystemVerilog based OVM and UVM Verification Methodologies
 
Jenkins CI
Jenkins CIJenkins CI
Jenkins CI
 
5 black box and grey box testing
5   black box and grey box testing5   black box and grey box testing
5 black box and grey box testing
 
Coverage and Introduction to UVM
Coverage and Introduction to UVMCoverage and Introduction to UVM
Coverage and Introduction to UVM
 
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus Introduction to DevOps. Continuous Integration by Myroslav Dmytrus
Introduction to DevOps. Continuous Integration by Myroslav Dmytrus
 
Gray box testing
Gray box testingGray box testing
Gray box testing
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdf
 
Dynamic Testing
Dynamic TestingDynamic Testing
Dynamic Testing
 

Destaque

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
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 

Destaque (20)

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
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 

Semelhante a 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
 

Semelhante a 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
 

Último

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

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