SlideShare una empresa de Scribd logo
1 de 49
1
C++ Testing Techniques, Tips and Tricks
Clare Macrae (She/her)
clare@claremacrae.co.uk
21 November 2019
C++ London
2
About Me
• Scientific C++ and Qt developer since 1999
• My mission: Sustainable and efficient testing and refactoring of legacy code
– Co-author of “Approval Tests for C++”
• Consulting & training via “Clare Macrae Consulting Ltd”
– https://claremacrae.co.uk
• All links from this talk via:
– github.com/claremacrae/talks
3
4
Why?
• Share things I wish I knew earlier
– Some well known
– Some less so…
• High-level overview, with links
– Avoiding detail
• Anything unclear?
– Please ask!
5
Getting Started Testing C++
6
Tip: Pick a Test Framework
• Lots to choose from, including:
• Get to know it well!
7
Tip: Practice!
8
Practice!
9
Scenario: Writing your first test
• Getting from 0 to 1 tests is always the hardest – that’s normal
• Getting from 1 to 2, and then 2 to 3, always much easier
• Step 1: Make the first test as easy as possible – it’s going to be hard!
• Step 2: Write at least 3 tests before deciding if it’s a good idea!
10
Techniques for Testing
11
Traditional unit tests
// Let Catch provide main():
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
int Factorial( int number ) {
return number <= 1 ? number : Factorial( number - 1 ) * number; // fail
// return number <= 1 ? 1 : Factorial( number - 1 ) * number; // pass
}
TEST_CASE( "Factorial of 0 is 1 (fail)", "[single-file]" ) {
REQUIRE( Factorial(0) == 1 );
}
TEST_CASE( "Factorials of 1 and higher are computed (pass)", "[single-file]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
12
Property Based Testing
• State the Invariants – what is required to be true
13
Kevlin Henney: FizzBuzz Trek HD
14
C++ Property Based Testing
• Can roll your own, in helper functions
• RapidCheck:
– github.com/emil-e/rapidcheck
15
Summary: Techniques for Testing
• Traditional Unit Tests
• Property Based Testing
16
Inheriting Legacy/Existing Code
17
Typical Scenario
• I've inherited some
legacy code
• It's valuable
• I need to add feature
• Or fix bug
• How can I ever break
out of this loop?
Need to
change
the code
No tests
Not
designed
for testing
Needs
refactoring
to add
tests
Can’t
refactor
without
tests
18
Typical Scenario
•
•
•
•
•
Need to
change
the code
No tests
Not
designed
for testing
Needs
refactoring
to add
tests
Can’t
refactor
without
tests
Topics of
this part
19
How good are your existing tests?
20
Measure Code Coverage
• Caution!
• Useful to see unexecuted code
• Use a code coverage tool
– What to measure?
21
Line Coverage: CLion 2019.3
22
Branch Coverage
23
Reference: Set-up on my Mac
• Slightly hard-won:
• g++-8
• CodeCoverage.cmake in github.com/bilke/cmake-modules
• lcov
• ~/.lcovrc
genhtml_branch_coverage = 1
lcov_branch_coverage = 1
lcov_excl_br_line = LCOV_EXCL_BR_LINE|CHECK|REQUIRE
24
Mutation testing: Sabotage the code!
• Test the tests
• Small changes
• Re-run tests
• Fail: 
• Pass: 
26
Golden Master Test Setup
Input
Data
Existing
Code
Save
“Golden
Master”
27
Golden Master Tests In Use
Input
Data
Updated
Code
Pass
Fail
Output
same?
Yes
No
28
Approval Tests
TEST_CASE( "Factorials up to 10" )
{
// Create a container with values 0 ... 10 inclusive
std::vector<int> inputs(11);
std::iota(inputs.begin(), inputs.end(), 0);
// Act on all values in inputs container:
Approvals::verifyAll("Factorial", inputs,
[](auto i, auto& os)
{
os << i << "! => " << Factorial(i);
});
}
29
Quickly Testing Legacy C++ Code
with Approval Tests
30
Scenario: Golden Master is a log file
• Dates and times?
• Object addresses?
2019-01-29 15:27
31
Options for unstable output
• Introduce date-time abstraction?
• Customised comparison function?
• Or: strip dates from the log file
32
Tip: Rewrite output file, before testing it
2019-01-29 15:27 [date-time-stamp]
33
Summary: Legacy Code
• Validating existing tests
– Consider Code coverage to validate initial tests
• Prefer Branch coverage to Line coverage
– Consider Mutation testing to break tests
• Consider Fuzz testing to find extra test cases
• Approval Tests
• Be creative to make your tests work for you!
34
Maintaining Tests
35
Scenario: Tests too slow for CI
• “Builds take 2 to 3 days!” => No hope of Continuous Integration
• Most of that was running tests
• No prospect of speeding up some very slow tests
36
Solution: Don’t run slow tests during day
• Mark some tests as Slow
– Filtering built in to Google Test Framework
• Teach CI system to run sub-set of tests
– Only run the Slow tests at night
– Everything else run on every commit
• Thanks to Michael Platings for making this happen!
37
Speeding up tests
• Incredible value of powerful tools for seeing where time goes
38
Tip: Never tolerate Flickering tests
• Tests that fail randomly
• Rapidly devalue other tests
• Fix them, or delete them!
• Especially don’t mix performance tests with unit tests
39
Summary: Maintaining Tests
• Fast feedback from Continuous Integration
• Stomp on flickering tests
40
Testing Qt User Interfaces
41
42
Qt’s GUI powers make
Automated Testing Harder
43
Introducing ApprovalTests.cpp.Qt
•Goals
• Rapid start testing Qt code
– Useful even if you don’t use Approval Tests!
• Approval Tests support for Qt types
– Easy saving of state in Golden Master files
• https://github.com/approvals/ApprovalTests.cpp.Qt
• https://github.com/approvals/ApprovalTests.cpp.Qt.StarterProject
• v.0.0.1
44
Example: Checking Table Contents
• Inherited complex code to set up a table
• Want to add at least a first test – of the text in the cells
45
Verifying a QTableWidget
TEST_CASE("It approves a QTableWidget")
{
// A note on naming: QTableWidget is a concrete class that implements
// the more general QTableView. Here we create a QTableWidget,
// for convenience.
QTableWidget tableWidget;
populateTable(tableWidget);
ApprovalTestsQt::verifyQTableView(tableWidget);
}
46
Approval file: .tsv
47
More Info…
• Key point: Use Fixtures to write Expressive, Maintainable Tests
– slideshare.net/ClareMacrae/quickly-testing-qt-desktop-applications
48
Summary
• It’s never too late to start testing!
– Pick a framework and practice it
– Explore different types of testing
• You can test legacy code too!
• Keep maintaining your tests
• Even GUIs can be tested
49
C++ Testing Techniques, Tips and Tricks
• All links from this talk, and more, via:
– github.com/claremacrae/talks
• Sustainable and efficient testing and refactoring of legacy code
• Consulting & training via “Clare Macrae Consulting Ltd”
– https://claremacrae.co.uk
– clare@claremacrae.co.uk
• Any Questions?
• Any More Tips?

Más contenido relacionado

La actualidad más candente

Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Thibaud Desodt
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cppClare Macrae
 
Testing Superpowers: Using CLion to Add Tests Easily
Testing Superpowers: Using CLion to Add Tests EasilyTesting Superpowers: Using CLion to Add Tests Easily
Testing Superpowers: Using CLion to Add Tests EasilyClare Macrae
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and backDavid Rodenas
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesDavid Rodenas
 
Unit testing for Cocoa developers
Unit testing for Cocoa developersUnit testing for Cocoa developers
Unit testing for Cocoa developersGraham Lee
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracleprohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
prohuddle-utPLSQL v3 - Ultimate unit testing framework for OracleJacek Gebal
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214David Rodenas
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven DevelopmentArif Huda
 
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
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 

La actualidad más candente (20)

Unit tests = maintenance hell ?
Unit tests = maintenance hell ? Unit tests = maintenance hell ?
Unit tests = maintenance hell ?
 
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cppQuickly and Effectively Testing Legacy c++ Code with Approval Tests   mu cpp
Quickly and Effectively Testing Legacy c++ Code with Approval Tests mu cpp
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Testing Superpowers: Using CLion to Add Tests Easily
Testing Superpowers: Using CLion to Add Tests EasilyTesting Superpowers: Using CLion to Add Tests Easily
Testing Superpowers: Using CLion to Add Tests Easily
 
Test box bdd
Test box bddTest box bdd
Test box bdd
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
TDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD TechniquesTDD CrashCourse Part3: TDD Techniques
TDD CrashCourse Part3: TDD Techniques
 
Unit testing for Cocoa developers
Unit testing for Cocoa developersUnit testing for Cocoa developers
Unit testing for Cocoa developers
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
Test driving QML
Test driving QMLTest driving QML
Test driving QML
 
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracleprohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
 
Test driving-qml
Test driving-qmlTest driving-qml
Test driving-qml
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
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++
 
TDD and BDD and ATDD
TDD and BDD and ATDDTDD and BDD and ATDD
TDD and BDD and ATDD
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 

Similar a C++ Testing Techniques Tips and Tricks - C++ London

Quickly Testing Legacy C++ Code with Approval Tests
Quickly Testing Legacy C++ Code with Approval TestsQuickly Testing Legacy C++ Code with Approval Tests
Quickly Testing Legacy C++ Code with Approval TestsClare Macrae
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++Matt Hargett
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
When assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsWhen assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsMartin Skurla
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyClare Macrae
 
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
 
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
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
QA Meetup at Signavio (Berlin, 06.06.19)
QA Meetup at Signavio (Berlin, 06.06.19)QA Meetup at Signavio (Berlin, 06.06.19)
QA Meetup at Signavio (Berlin, 06.06.19)Anesthezia
 
Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Brian Okken
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best PracticesTomaš Maconko
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Codecamp Romania
 
Lean-Agile Development with SharePoint - Bill Ayers
Lean-Agile Development with SharePoint - Bill AyersLean-Agile Development with SharePoint - Bill Ayers
Lean-Agile Development with SharePoint - Bill AyersSPC Adriatics
 
Property based testing - Less is more
Property based testing - Less is moreProperty based testing - Less is more
Property based testing - Less is moreHo Tien VU
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)Rob Hale
 
How to become a testing expert
How to become a testing expertHow to become a testing expert
How to become a testing expertgaoliang641
 
[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
 
Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceJitendra Zaa
 

Similar a C++ Testing Techniques Tips and Tricks - C++ London (20)

Quickly Testing Legacy C++ Code with Approval Tests
Quickly Testing Legacy C++ Code with Approval TestsQuickly Testing Legacy C++ Code with Approval Tests
Quickly Testing Legacy C++ Code with Approval Tests
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
When assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() failsWhen assertthat(you).understandUnitTesting() fails
When assertthat(you).understandUnitTesting() fails
 
How to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ EffectivelyHow to use Approval Tests for C++ Effectively
How to use Approval Tests for C++ Effectively
 
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
 
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)
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
QA Meetup at Signavio (Berlin, 06.06.19)
QA Meetup at Signavio (Berlin, 06.06.19)QA Meetup at Signavio (Berlin, 06.06.19)
QA Meetup at Signavio (Berlin, 06.06.19)
 
Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1Multiply your Testing Effectiveness with Parameterized Testing, v1
Multiply your Testing Effectiveness with Parameterized Testing, v1
 
Unit Testing Best Practices
Unit Testing Best PracticesUnit Testing Best Practices
Unit Testing Best Practices
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
 
Lean-Agile Development with SharePoint - Bill Ayers
Lean-Agile Development with SharePoint - Bill AyersLean-Agile Development with SharePoint - Bill Ayers
Lean-Agile Development with SharePoint - Bill Ayers
 
Property based testing - Less is more
Property based testing - Less is moreProperty based testing - Less is more
Property based testing - Less is more
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
How to become a testing expert
How to become a testing expertHow to become a testing expert
How to become a testing expert
 
[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
 
Episode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in SalesforceEpisode 5 - Writing unit tests in Salesforce
Episode 5 - Writing unit tests in Salesforce
 

Más de Clare Macrae

Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsClare Macrae
 
Code samples that actually compile - Clare Macrae
Code samples that actually compile - Clare MacraeCode samples that actually compile - Clare Macrae
Code samples that actually compile - Clare MacraeClare Macrae
 
Quickly testing legacy code cppp.fr 2019 - clare macrae
Quickly testing legacy code   cppp.fr 2019 - clare macraeQuickly testing legacy code   cppp.fr 2019 - clare macrae
Quickly testing legacy code cppp.fr 2019 - clare macraeClare Macrae
 
Quickly Testing Legacy Code - ACCU York April 2019
Quickly Testing Legacy Code - ACCU York April 2019Quickly Testing Legacy Code - ACCU York April 2019
Quickly Testing Legacy Code - ACCU York April 2019Clare Macrae
 
Quickly testing legacy code
Quickly testing legacy codeQuickly testing legacy code
Quickly testing legacy codeClare Macrae
 
Escaping 5 decades of monolithic annual releases
Escaping 5 decades of monolithic annual releasesEscaping 5 decades of monolithic annual releases
Escaping 5 decades of monolithic annual releasesClare Macrae
 
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...Clare Macrae
 

Más de Clare Macrae (7)

Quickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop ApplicationsQuickly Testing Qt Desktop Applications
Quickly Testing Qt Desktop Applications
 
Code samples that actually compile - Clare Macrae
Code samples that actually compile - Clare MacraeCode samples that actually compile - Clare Macrae
Code samples that actually compile - Clare Macrae
 
Quickly testing legacy code cppp.fr 2019 - clare macrae
Quickly testing legacy code   cppp.fr 2019 - clare macraeQuickly testing legacy code   cppp.fr 2019 - clare macrae
Quickly testing legacy code cppp.fr 2019 - clare macrae
 
Quickly Testing Legacy Code - ACCU York April 2019
Quickly Testing Legacy Code - ACCU York April 2019Quickly Testing Legacy Code - ACCU York April 2019
Quickly Testing Legacy Code - ACCU York April 2019
 
Quickly testing legacy code
Quickly testing legacy codeQuickly testing legacy code
Quickly testing legacy code
 
Escaping 5 decades of monolithic annual releases
Escaping 5 decades of monolithic annual releasesEscaping 5 decades of monolithic annual releases
Escaping 5 decades of monolithic annual releases
 
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...
CCDC’s (ongoing) Journey to Continuous Delivery - London Continuous Delivery ...
 

Último

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 

Último (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

C++ Testing Techniques Tips and Tricks - C++ London

  • 1. 1 C++ Testing Techniques, Tips and Tricks Clare Macrae (She/her) clare@claremacrae.co.uk 21 November 2019 C++ London
  • 2. 2 About Me • Scientific C++ and Qt developer since 1999 • My mission: Sustainable and efficient testing and refactoring of legacy code – Co-author of “Approval Tests for C++” • Consulting & training via “Clare Macrae Consulting Ltd” – https://claremacrae.co.uk • All links from this talk via: – github.com/claremacrae/talks
  • 3. 3
  • 4. 4 Why? • Share things I wish I knew earlier – Some well known – Some less so… • High-level overview, with links – Avoiding detail • Anything unclear? – Please ask!
  • 6. 6 Tip: Pick a Test Framework • Lots to choose from, including: • Get to know it well!
  • 9. 9 Scenario: Writing your first test • Getting from 0 to 1 tests is always the hardest – that’s normal • Getting from 1 to 2, and then 2 to 3, always much easier • Step 1: Make the first test as easy as possible – it’s going to be hard! • Step 2: Write at least 3 tests before deciding if it’s a good idea!
  • 11. 11 Traditional unit tests // Let Catch provide main(): #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> int Factorial( int number ) { return number <= 1 ? number : Factorial( number - 1 ) * number; // fail // return number <= 1 ? 1 : Factorial( number - 1 ) * number; // pass } TEST_CASE( "Factorial of 0 is 1 (fail)", "[single-file]" ) { REQUIRE( Factorial(0) == 1 ); } TEST_CASE( "Factorials of 1 and higher are computed (pass)", "[single-file]" ) { REQUIRE( Factorial(1) == 1 ); REQUIRE( Factorial(2) == 2 ); REQUIRE( Factorial(3) == 6 ); REQUIRE( Factorial(10) == 3628800 ); }
  • 12. 12 Property Based Testing • State the Invariants – what is required to be true
  • 14. 14 C++ Property Based Testing • Can roll your own, in helper functions • RapidCheck: – github.com/emil-e/rapidcheck
  • 15. 15 Summary: Techniques for Testing • Traditional Unit Tests • Property Based Testing
  • 17. 17 Typical Scenario • I've inherited some legacy code • It's valuable • I need to add feature • Or fix bug • How can I ever break out of this loop? Need to change the code No tests Not designed for testing Needs refactoring to add tests Can’t refactor without tests
  • 18. 18 Typical Scenario • • • • • Need to change the code No tests Not designed for testing Needs refactoring to add tests Can’t refactor without tests Topics of this part
  • 19. 19 How good are your existing tests?
  • 20. 20 Measure Code Coverage • Caution! • Useful to see unexecuted code • Use a code coverage tool – What to measure?
  • 23. 23 Reference: Set-up on my Mac • Slightly hard-won: • g++-8 • CodeCoverage.cmake in github.com/bilke/cmake-modules • lcov • ~/.lcovrc genhtml_branch_coverage = 1 lcov_branch_coverage = 1 lcov_excl_br_line = LCOV_EXCL_BR_LINE|CHECK|REQUIRE
  • 24. 24 Mutation testing: Sabotage the code! • Test the tests • Small changes • Re-run tests • Fail:  • Pass: 
  • 25.
  • 26. 26 Golden Master Test Setup Input Data Existing Code Save “Golden Master”
  • 27. 27 Golden Master Tests In Use Input Data Updated Code Pass Fail Output same? Yes No
  • 28. 28 Approval Tests TEST_CASE( "Factorials up to 10" ) { // Create a container with values 0 ... 10 inclusive std::vector<int> inputs(11); std::iota(inputs.begin(), inputs.end(), 0); // Act on all values in inputs container: Approvals::verifyAll("Factorial", inputs, [](auto i, auto& os) { os << i << "! => " << Factorial(i); }); }
  • 29. 29 Quickly Testing Legacy C++ Code with Approval Tests
  • 30. 30 Scenario: Golden Master is a log file • Dates and times? • Object addresses? 2019-01-29 15:27
  • 31. 31 Options for unstable output • Introduce date-time abstraction? • Customised comparison function? • Or: strip dates from the log file
  • 32. 32 Tip: Rewrite output file, before testing it 2019-01-29 15:27 [date-time-stamp]
  • 33. 33 Summary: Legacy Code • Validating existing tests – Consider Code coverage to validate initial tests • Prefer Branch coverage to Line coverage – Consider Mutation testing to break tests • Consider Fuzz testing to find extra test cases • Approval Tests • Be creative to make your tests work for you!
  • 35. 35 Scenario: Tests too slow for CI • “Builds take 2 to 3 days!” => No hope of Continuous Integration • Most of that was running tests • No prospect of speeding up some very slow tests
  • 36. 36 Solution: Don’t run slow tests during day • Mark some tests as Slow – Filtering built in to Google Test Framework • Teach CI system to run sub-set of tests – Only run the Slow tests at night – Everything else run on every commit • Thanks to Michael Platings for making this happen!
  • 37. 37 Speeding up tests • Incredible value of powerful tools for seeing where time goes
  • 38. 38 Tip: Never tolerate Flickering tests • Tests that fail randomly • Rapidly devalue other tests • Fix them, or delete them! • Especially don’t mix performance tests with unit tests
  • 39. 39 Summary: Maintaining Tests • Fast feedback from Continuous Integration • Stomp on flickering tests
  • 40. 40 Testing Qt User Interfaces
  • 41. 41
  • 42. 42 Qt’s GUI powers make Automated Testing Harder
  • 43. 43 Introducing ApprovalTests.cpp.Qt •Goals • Rapid start testing Qt code – Useful even if you don’t use Approval Tests! • Approval Tests support for Qt types – Easy saving of state in Golden Master files • https://github.com/approvals/ApprovalTests.cpp.Qt • https://github.com/approvals/ApprovalTests.cpp.Qt.StarterProject • v.0.0.1
  • 44. 44 Example: Checking Table Contents • Inherited complex code to set up a table • Want to add at least a first test – of the text in the cells
  • 45. 45 Verifying a QTableWidget TEST_CASE("It approves a QTableWidget") { // A note on naming: QTableWidget is a concrete class that implements // the more general QTableView. Here we create a QTableWidget, // for convenience. QTableWidget tableWidget; populateTable(tableWidget); ApprovalTestsQt::verifyQTableView(tableWidget); }
  • 47. 47 More Info… • Key point: Use Fixtures to write Expressive, Maintainable Tests – slideshare.net/ClareMacrae/quickly-testing-qt-desktop-applications
  • 48. 48 Summary • It’s never too late to start testing! – Pick a framework and practice it – Explore different types of testing • You can test legacy code too! • Keep maintaining your tests • Even GUIs can be tested
  • 49. 49 C++ Testing Techniques, Tips and Tricks • All links from this talk, and more, via: – github.com/claremacrae/talks • Sustainable and efficient testing and refactoring of legacy code • Consulting & training via “Clare Macrae Consulting Ltd” – https://claremacrae.co.uk – clare@claremacrae.co.uk • Any Questions? • Any More Tips?

Notas del editor

  1. Note of caution: knowing that a line of code is executed tells nothing about if it was tested! Still useful to see totally un-tested code Techniques Run in debugger with breakpoints, to see what lines are reached Run through code coverage tool to at least see what lines are executed But what do you measure?
  2. Another phrase for the Golden Master output is “Known Good” output.
  3. Harder than testing non-Graphical User Interface code But it’s still a learnable skill
  4. A lot of this stuff you can get going on your own. If you get stuck, I can help you!