SlideShare a Scribd company logo
1 of 52
Download to read offline
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Writing Unit Tests with Google Testing Framework
Humberto Cardoso Marchezi
hcmarchezi@gmail.com
May 31, 2015
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Table of Contents
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Test levels
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Unit tests characteristics
Fast
Isolated
Repeatable
Self-verifying
Timely
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
We will follow the steps:
1 Identify test cases
2 Share test cases with others
3 Write one test case as a unit test
4 Watch test failing
5 Write just enough code to pass test
6 Clean up code
7 Go to step 3 until all tests are done
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Identify test cases
Problem: implement function for factorial operation
5! = 5 x 4 x 3 x 2 x 1 = 120
4! = 4 x 3 x 2 x 1 = 24
0! = 1
test case expected behavior
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Identify test cases
Problem: implement function for factorial operation
test case expected behavior
small positive numbers should calculate factorial
input value is 0 should return 1
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Share test cases with others
Problem: implement function for factorial operation
test case expected behavior
small positive numbers should calculate factorial
input value is 0 should return 1
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Factorial table
n factorial(n)
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
20 2432902008176640000
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Share test cases with others
Problem: implement function for factorial operation
test case expected behavior
small positive numbers should calculate factorial
input value is 0 should return 1
input value is negative return error code
input value is a bigger
positive integer
return overflow error code
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Write one test case as a unit test
test case expected behavior
input value is 0 should return 1
TEST( F a c t o r i a l T e s t , FactorialOfZeroShouldBeOne )
{
ASSERT EQ(1 , f a c t o r i a l (0) ) ; // 0! == 1
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Write just enough code to pass test
For a test like this:
TEST( F a c t o r i a l T e s t , FactorialOfZeroShouldBeOne )
{
ASSERT EQ(1 , f a c t o r i a l (0) ) ; // 0! == 1
}
Focus on code to ONLY make it pass like this:
i n t f a c t o r i a l ( i n t n )
{
r e t u r n 1;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Clean up code
Clean up accumulated mess
Refactorings
Optimizations
Readability
Modularity
Don’t miss this step!
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Go to next test
TEST( F a c t o r i a l T e s t , F a c t O f S m a l l P o s i t i v e I n t e g e r s )
{
ASSERT EQ(1 , f a c t o r i a l (1) ) ;
ASSERT EQ(24 , f a c t o r i a l (4) ) ;
ASSERT EQ(120 , f a c t o r i a l (5) ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Why ?
Portable: Works for Windows, Linux and Mac
Familiar: Similar to other xUnit frameworks (JUnit, PyUnit,
etc.)
Simple: Unit tests are small and easy to read
Popular: Many users and available documentation
Powerful: Allows advanced configuration if needed
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Tests
TEST ( ) macro defines a test name and function
TEST( test case name , test name )
{
. . . t e s t body . . .
}
Example:
TEST( FibonacciTest , CalculateSeedValues )
{
ASSERT EQ(0 , Fibonacci (0) ) ;
ASSERT EQ(1 , Fibonacci (1) ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Assertions
Checks expected behavior for function or method
ASSERT * fatal failures (test is interrupted)
EXPECT * non-fatal failures
Operator <<custom failure message
ASSERT EQ( x . s i z e () , y . s i z e () ) <<
” Vectors x and y are of unequal l ength ” ;
f o r ( i n t i = 0; i < x . s i z e () ; ++i )
{
EXPECT EQ( x [ i ] , y [ i ] ) <<
” Vectors x and y d i f f e r at index ” << i ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Assertions
Logic assertions
Description Fatal assertion Non-fatal assertion
True condition ASSERT TRUE(condition); EXPECT TRUE(condition);
False condition ASSERT FALSE(condition); EXPECT FALSE(condition);
Integer assertions
Description Fatal assertion Non-fatal assertion
Equal ASSERT EQ(expected, actual); EXPECT EQ(expected, actual);
Less then ASSERT LT(expected, actual); EXPECT LT(expected, actual);
Less or equal
then
ASSERT LE(expected, actual); EXPECT LE(expected, actual);
Greater then ASSERT GT(expected, actual); EXPECT GT(expected, actual);
Greater or
equal then
ASSERT GE(expected, actual); EXPECT GE(expected, actual);
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Assertions
String assertions
Description Fatal assertion Non-fatal assertion
Different content ASSERT STRNE(exp, actual); EXPECT STREQ(exp, actual);
Same content, ig-
noring case
ASSERT STRCASEEQ(exp,actual); EXPECT STRCASEEQ(exp,actual);
Different content,
ignoring case
ASSERT STRCASENE(exp,actual); EXPECT STRCASEEQ(exp,actual);
Explicit assertions
Description Assertion
Explicit success SUCCEED();
Explicit fatal failure FAIL();
Explicit non-fatal failure ADD FAILURE();
Explicit non-fatal failure
with detailed message
ADD FAILURE AT(”file path”,linenumber);
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Assertions
Exception assertions
Description Fatal assertion Non-fatal assertion
Exception type
was thrown
ASSERT THROW(statement,exception); EXPECT THROW(statement, exception);
Any exception
was thrown
ASSERT ANY THROW(statement); EXPECT ANY THROW(statement);
No exception
thrown
ASSERT NO THROW(statement); EXPECT NO THROW(statement);
Floating point number assertions
Description Fatal assertion Non-fatal assertion
Double compari-
son
ASSERT DOUBLE EQ(expected, actual); EXPECT DOUBLE EQ(expected, actual);
Float comparison ASSERT FLOAT EQ(expected, actual); EXPECT FLOAT EQ(expected, actual);
Float point com-
parison with mar-
gin of error
ASSERT NEAR(val1, val2, abse rror); EXPECT NEAR(val1, val2, abse rror);
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Test fixtures
Definition:
Tests that operate on similar data
c l a s s LogTests : p u b l i c : : t e s t i n g : : Test {
p r o t e c t e d :
void SetUp () { . . . } // Prepare data f o r each t e s t
void TearDown () { . . . } // Release data f o r each t e s t
i n t auxMethod ( . . . ) { . . . }
}
TEST F ( LogTests , c l e a n L o g F i l e s ) {
. . . t e s t body . . .
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Controlling execution
Run all tests
mytestprogram . exe
Runs ”SoundTest” test cases
mytestprogram . exe − g t e s t f i l t e r=SoundTest .∗
Runs tests whose name contains ”Null” or ”Constructor”
mytestprogram . exe − g t e s t f i l t e r =∗Null ∗:∗ Constructor
∗
Runs tests except those whose preffix is ”DeathTest”
mytestprogram . exe − g t e s t f i l t e r =−∗DeathTest .∗
Run ”FooTest” test cases except ”testCase3”
mytestprogram . exe − g t e s t f i l t e r=FooTest.∗−FooTest .
testCase3
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Controlling execution
Temporarily Disabling Tests
For test cases, add DISABLED preffix
TEST( SoundTest , DISABLED legacyProcedure ) { . . . }
For all tests cases in test fixture, add DISABLED to test fixture name
c l a s s DISABLED VectTest : p u b l i c : : t e s t i n g : : Test
{ . . . };
TEST F ( DISABLED ArrayTest , testCase4 ) { . . . }
Enabling execution of disabled tests
mytest . exe −−g t e s t a l s o r u n d i s a b l e d t e s t s
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Output customization
Invoking tests with output customization
mytest program . exe −−g t e s t o u t p u t =”xml : d i r e c t o r y 
m y f i l e . xml”
XML format (JUnit compatible)
<t e s t s u i t e s name=” A l l T e s t s ” . . .>
<t e s t s u i t e name=” test case name ” . . .>
<t e s t c a s e name=” test name ” . . .>
<f a i l u r e message=” . . . ”/>
<f a i l u r e message=” . . . ”/>
<f a i l u r e message=” . . . ”/>
</ t e s t c a s e>
</ t e s t s u i t e>
</ t e s t s u i t e s>
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Output customization
Listing test names (without executing them)
mytest program . exe −−g t e s t l i s t t e s t s
TestCase1 .
TestName1
TestName2
TestCase2 .
TestName
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Advanced features
Predicate assertions
AssertionResult
Predicate formatter
Windows HRESULT assertions
Type assertions
Customizing value type serialization
Death tests
Logging additional information in XML output
Value parametized tests Etc ...
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Types of functions
Testing functions
From testing perspective, there are mainly 3 types of functions:
functions with input and output.
Ex: math functions
functions with input and object side-effect.
Ex: person.setName(’John’);
functions with input and not testable side-effect.
Ex: drawLine(30,30,120,190);
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Types of functions
Functions with input and output
the easiest case - direct implementation
functions should be refactored to this format when possible
TEST( FibonacciTest , FibonacciOfZeroShouldBeZero ) {
ASSERT EQ(0 , f i b o n a c c i (0) ) ;
}
TEST( FibonacciTest , FibonacciOfOneShouldBeOne ) {
ASSERT EQ(1 , f i b o n a c c i (1) ) ;
}
TEST( FibonacciTest , F i b o n a c c i O f S m a l l P o s i t i v e I n t e g e r s ) {
ASSERT EQ(2 , f i b o n a c c i (3) ) ;
ASSERT EQ(3 , f i b o n a c c i (4) ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Types of functions
Functions with input and object side-effect
not so direct but still easy
object should contain a read method to check state
TEST( PersonTest , SetBirthDateShouldModifyAge ) {
Person p ;
p . setBirthDate ( ”1978−09−16” ) ;
ASSERT STR EQ(36 , p . age () ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Types of functions
Functions with input and not testable side-effect
can’t test what we can’t measure (in code)
effort is not worth for unit testing
TEST( DisplayTest , LineShouldBeDisplayed ) {
Display d i s p l a y ;
d i s p l a y . drawLine (20 ,34 ,100 ,250) ;
??????????? − How to a s s e r t t h i s ???
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Configuration and implementation
Isolate configuration from the actual code
How to test Init failure in this code ?
c l a s s Component {
p u b l i c :
i n t i n i t () {
i f ( XYZ License ( ” key abcdefg ” ) != 0) {
r e t u r n INIT FAILURE ;
}
r e t u r n INIT SUCCESS ;
}
};
’init’ is a function without testable side-effects
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Configuration and implementation
Isolate configuration from the actual code
Instead separate configuration from code
c l a s s Component
{
p r o t e c t e d :
std : : s t r i n g l i c e n s e = ” key abcdefg ” ;
p u b l i c :
i n t i n i t () {
i f ( XYZ License ( l i c e n s e ) == FAILURE)
{
r e t u r n INIT FAILURE ;
}
}
};
License information became an object variable
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Configuration and implementation
Isolate configuration from the actual code
Extend class to add methods to access protected information
c l a s s TestableComponent : p u b l i c Component
{
p u b l i c :
void s e t L i c e n s e ( s t r i n g l i c e n s e ) {
t h i s . l i c e n s e = l i c e n s e ;
}
};
’setLicense’ is necessary to modify the state of ’init’ method
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Configuration and implementation
Isolate configuration from the actual code
Now the test becomes possible:
TEST( ComponentTest , U p o n I n i t i a l i z a t i o n F a i l u r e S h o u l d
Return ErrorCode )
{
// A u x i l i a r t e s t c l a s s can be d e c l a r e d only
// i n the scope of the t e s t
c l a s s TestableComponent : p u b l i c Component
{
p u b l i c :
void s e t L i c e n s e ( s t r i n g l i c e n s e ) {
t h i s . l i c e n s e = l i c e n s e ;
}
};
TestableComponent component ;
component . s e t L i c e n s e ( ”FAKE LICENSE” ) ;
ASSERT EQ( INIT FAILURE , component . i n i t () ) ;
};
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Extract your application
Separate app logic from presentation
Presentation logic refers to UI components to show user
feedback
Application logic refers to data transformation upon user or
other system input
Presentation and logic should be separated concerns
Presentation is usually not unit testable
Application logic is usually testable
std : : s t r i n g name = u i . txtName . t e x t () ;
std : : s i z e t p o s i t i o n = name . f i n d ( ” ” ) ;
std : : s t r i n g firstName = name . s u b s t r (0 , p o s i t i o n ) ;
std : : s t r i n g lastName = name . s u b s t r ( p o s i t i o n ) ;
u i . l b D e s c r i p t i o n . setText ( lastName + ” , ” + firstName ) ;
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
Extract your application
Separate app logic from presentation
Extract app logic in a separated function (preferrebly class)
std : : s t r i n g name = u i . txtName . t e x t () ;
std : : s t r i n g d e s c r i p t i o n = app . makeDescription (name) ;
u i . l b D e s c r i p t i o n . setText ( d e s c r i p t i o n ) ;
TEST( ApplicationTest , shouldMakeDescription ) {
A p p l i c a t i o n app ;
std : : s t r i n g d e s c r i p t i o n ;
d e s c r i p t i o n = app . makeDescription ( ”James O l i v e r ” ) ;
ASSERT STREQ( ” Oliver , James” , d e s c r i p t i o n ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Code with mixed responsibilities
HttpResponse response ;
response = http . get ( ” http :// domain/ api / contry code ” +
”? token=” + token ) ;
std : : s t r i n g countryCode = response . body ;
std : : s t r i n g langCode ;
i f ( countryCode == BRAZIL) {
langCode = PORTUGUESE;
} e l s e i f ( countryCode == USA) {
langCode = ENGLISH ;
} e l s e {
langCode = ENGLISH ;
}
u i . setLanguage ( langCode ) ;
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Identify and isolate dependency
WebAPIGateway webAPI ;
std : : s t r i n g countryCode=webAPI . userCountryCode ( token ) ;
LanguageHelper language ;
std : : s t r i n g langCode=language . findLang ( countryCode ) ;
u i . setLanguage ( langCode ) ;
TEST( LanguageHelperTest , shouldFindLanguageForCountry )
{
LanguageHelper language ;
ASSERT EQ(PORTUGUESE, language . findLang (BRAZIL) ) ;
ASSERT EQ(ENGLISH , language . findLang (USA) ) ;
ASSERT EQ(ENGLISH , language . findLang (JAPAN) ) ;
. . .
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Fake objects
#i n c l u d e ”gmock/gmock . h”
TEST( WebAPIGatewayTest , shouldFindUserCountry ) {
c l a s s HttpRequestFake : p u b l i c HttpRequest
{
std : : s t r i n g userCountryCode ( std : : s t r i n g token ) {
std : : s t r i n g country = ”” ;
i f ( token==”abc” ) country = BRAZIL ;
r e t u r n country ;
}
};
HttpRequest ∗ httpFake = new HttpRequestFake () ;
WebAPIGateway api = WebAPIGateway ( httpFake ) ;
std : : s t r i n g countryCode = api . userCountryCode ( ”abc” ) ;
d e l e t e httpFake ;
ASSERT EQ(BRAZIL , countryCode ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Mock objects
#i n c l u d e ”gmock/gmock . h”
c l a s s HttpRequestMock : p u b l i c HttpRequest
{
MOCK CONST METHOD1( get () , std : : s t r i n g ( std : : s t r i n g ) ) ;
};
TEST( WebAPIGatewayTest , shouldFindUserCountry ) {
HttpRequest ∗ httpMock = new HttpRequestMock () ;
WebAPIGateway api = WebAPIGateway ( httpMock ) ;
EXPECT CALL( httpMock ,
get ( ” http :// domain/ api / contry code ? token=abc” )
. Times (1)
. WillOnce ( Return ( Response (BRAZIL) ) ) ;
std : : s t r i n g countryCode = api . userCountryCode ( ”abc” ) ;
d e l e t e httpMock ;
ASSERT EQ(BRAZIL , countryCode ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Code with dependencies
How to test vertices coordinates calculation ?
void drawQuad ( f l o a t cx , f l o a t cy , f l o a t s i d e )
{
f l o a t h a l f S i d e = s i d e / 2 . 0 ;
glBegin (GL LINE LOOP) ;
g l V e r t e x 3 f ( cx−h a l f S i d e , cy−h a l f S i d e ) ;
g l V e r t e x 3 f ( cx+h a l f S i d e , cy−h a l f S i d e ) ;
g l V e r t e x 3 f ( cx+h a l f S i d e , cy+h a l f S i d e ) ;
g l V e r t e x 3 f ( cx−h a l f S i d e , cy+h a l f S i d e ) ;
glEnd () ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Identify and isolate dependency
void drawQuad ( f l o a t cx , f l o a t cy , f l o a t side ,
I D i s p l a y ∗ d i s p l a y {
f l o a t h a l f S i d e = s i d e / 2 . 0 ;
std : : vector <f l o a t > v e r t i c e s = {
cx−h a l f S i d e , cy−h a l f S i d e ,
cx+h a l f S i d e , cy−h a l f S i d e ,
cx+h a l f S i d e , cy+h a l f S i d e ,
cx−h a l f S i d e , cy+h a l f S i d e
};
d i s p l a y −>r e c t a n g l e ( v e r t i c e s ) ;
}
c l a s s Display : p u b l i c I D i s p l a y {
p u b l i c : void r e c t a n g l e ( std : : vector <f l o a t > v e r t i c e s ) {
glBegin (GL LINE LOOP) ;
g l V e r t e x 3 f ( v e r t i c e s [ 0 ] , v e r t i c e s [ 1 ] ) ;
. . .
glEnd () ;
} };
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Fake objects
TEST( DrawTests , drawQuadShouldCalculateVertices ) {
c l a s s FakeDisplay : p u b l i c Display {
p r o t e c t e d : std : : vector <f l o a t > v e r t i c e s ;
p u b l i c :
void r e c t a n g l e ( std : : vector <f l o a t > v e r t i c e s ) {
v e r t i c e s = v e r t i c e s ;
}
std : : vector <f l o a t > v e r t i c e s () {
r e t u r n v e r t i c e s ;
}
};
I D i s p l a y ∗ d i s p l a y = new FakeDisplay () ;
drawQuad ( 1 0 . 0 , 1 0 . 0 , 1 0 . 0 , d i s p l a y ) ;
ASSERT VECT EQ(
{ 5 . 0 , 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 } ,
d i s p l a y −>v e r t i c e s () ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
External dependencies
Mock objects
#i n c l u d e ”gmock/gmock . h”
TEST( DrawTests , drawQuadShouldCalculateVertices ) {
c l a s s MockDisplay : p u b l i c Display {
MOCK METHOD1( r e c t a n g l e , void ( std : : vector <f l o a t >) ;
};
I D i s p l a y ∗ d i s p l a y = new MockDisplay () ;
EXPECT CALL( d i s p l a y ,
r e c t a n g l e ( { 5 . 0 , 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 } )
. Times (1)
drawQuad ( 1 0 . 0 , 1 0 . 0 , 1 0 . 0 , d i s p l a y ) ;
}
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
General tips
Test behavior not implementation
There is no behavior in non-public methods
Use name convention for tests to improve readability
Test code should be as good as production code - it is not
sketch code
GTest alone can’t help you
Workflow is important - talk to your QA
Improve modularization to avoid being trapped by non
testable code
Use mock objects with caution
Understand the difference between fake and mock objects
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
1 What is a unit test?
2 How to get started ?
3 GTest - basics
Why ?
Tests
Assertions
Test fixtures
Controlling execution
Output customization
Advanced features
4 Make code testable
Types of functions
Configuration and
implementation
Extract your application
External dependencies
5 General tips
6 References
What is a unit test? How to get started ? GTest - basics Make code testable General tips References
General tips
Getting Started with Google Testing Framework
https://code.google.com/p/googletest/wiki/Primer
GTest Advanced Guide
https://code.google.com/p/googletest/wiki/AdvancedGuide
Clean Code: A Handbook of Agile Software Craftsmanship
Robert C. Martin - Prentice Hall PTR, 2009
Google C++ Mocking Framework for Dummies
https://code.google.com/p/googlemock/wiki/ForDummies

More Related Content

What's hot

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentTung Nguyen Thanh
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentJohn Blum
 
05 junit
05 junit05 junit
05 junitmha4
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4ICS
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytestviniciusban
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing frameworkIgor Vavrish
 

What's hot (20)

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
05 junit
05 junit05 junit
05 junit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit testing
Unit testingUnit testing
Unit testing
 
Junit
JunitJunit
Junit
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Junit
JunitJunit
Junit
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
 

Similar to Getting Started With Unit Testing in C++ Using GTest

DSR Testing (Part 1)
DSR Testing (Part 1)DSR Testing (Part 1)
DSR Testing (Part 1)Steve Upton
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaQA or the Highway
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easierChristian Hujer
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTscatherinewall
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017Xavi Hidalgo
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)Amr E. Mohamed
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Project
 

Similar to Getting Started With Unit Testing in C++ Using GTest (20)

DSR Testing (Part 1)
DSR Testing (Part 1)DSR Testing (Part 1)
DSR Testing (Part 1)
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Shift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David LaulusaShift-Left Testing: QA in a DevOps World by David Laulusa
Shift-Left Testing: QA in a DevOps World by David Laulusa
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier2016 10-04: tdd++: tdd made easier
2016 10-04: tdd++: tdd made easier
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Rc2010 tdd
Rc2010 tddRc2010 tdd
Rc2010 tdd
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
STAMP Descartes Presentation
STAMP Descartes PresentationSTAMP Descartes Presentation
STAMP Descartes Presentation
 

More from Humberto Marchezi

Anomaly Detection in Seasonal Time Series
Anomaly Detection in Seasonal Time SeriesAnomaly Detection in Seasonal Time Series
Anomaly Detection in Seasonal Time SeriesHumberto Marchezi
 
Building Anomaly Detections Systems
Building Anomaly Detections SystemsBuilding Anomaly Detections Systems
Building Anomaly Detections SystemsHumberto Marchezi
 
Getting Started with Machine Learning
Getting Started with Machine LearningGetting Started with Machine Learning
Getting Started with Machine LearningHumberto Marchezi
 
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...Humberto Marchezi
 

More from Humberto Marchezi (7)

Anomaly Detection in Seasonal Time Series
Anomaly Detection in Seasonal Time SeriesAnomaly Detection in Seasonal Time Series
Anomaly Detection in Seasonal Time Series
 
Building Anomaly Detections Systems
Building Anomaly Detections SystemsBuilding Anomaly Detections Systems
Building Anomaly Detections Systems
 
Getting Started with Machine Learning
Getting Started with Machine LearningGetting Started with Machine Learning
Getting Started with Machine Learning
 
Machine Learning Basics
Machine Learning BasicsMachine Learning Basics
Machine Learning Basics
 
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...
Um Ambiente Grafico para Desenvolvimento de Software de Controle para Robos M...
 
NHibernate
NHibernateNHibernate
NHibernate
 
Padroes de desenho
Padroes de desenhoPadroes de desenho
Padroes de desenho
 

Recently uploaded

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 

Getting Started With Unit Testing in C++ Using GTest

  • 1. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Writing Unit Tests with Google Testing Framework Humberto Cardoso Marchezi hcmarchezi@gmail.com May 31, 2015
  • 2. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Table of Contents 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 3. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 4. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Test levels
  • 5. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Unit tests characteristics Fast Isolated Repeatable Self-verifying Timely
  • 6. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 7. What is a unit test? How to get started ? GTest - basics Make code testable General tips References We will follow the steps: 1 Identify test cases 2 Share test cases with others 3 Write one test case as a unit test 4 Watch test failing 5 Write just enough code to pass test 6 Clean up code 7 Go to step 3 until all tests are done
  • 8. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Identify test cases Problem: implement function for factorial operation 5! = 5 x 4 x 3 x 2 x 1 = 120 4! = 4 x 3 x 2 x 1 = 24 0! = 1 test case expected behavior
  • 9. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Identify test cases Problem: implement function for factorial operation test case expected behavior small positive numbers should calculate factorial input value is 0 should return 1
  • 10. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Share test cases with others Problem: implement function for factorial operation test case expected behavior small positive numbers should calculate factorial input value is 0 should return 1
  • 11. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Factorial table n factorial(n) 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 10 3628800 11 39916800 12 479001600 20 2432902008176640000
  • 12. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Share test cases with others Problem: implement function for factorial operation test case expected behavior small positive numbers should calculate factorial input value is 0 should return 1 input value is negative return error code input value is a bigger positive integer return overflow error code
  • 13. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Write one test case as a unit test test case expected behavior input value is 0 should return 1 TEST( F a c t o r i a l T e s t , FactorialOfZeroShouldBeOne ) { ASSERT EQ(1 , f a c t o r i a l (0) ) ; // 0! == 1 }
  • 14. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Write just enough code to pass test For a test like this: TEST( F a c t o r i a l T e s t , FactorialOfZeroShouldBeOne ) { ASSERT EQ(1 , f a c t o r i a l (0) ) ; // 0! == 1 } Focus on code to ONLY make it pass like this: i n t f a c t o r i a l ( i n t n ) { r e t u r n 1; }
  • 15. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Clean up code Clean up accumulated mess Refactorings Optimizations Readability Modularity Don’t miss this step!
  • 16. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Go to next test TEST( F a c t o r i a l T e s t , F a c t O f S m a l l P o s i t i v e I n t e g e r s ) { ASSERT EQ(1 , f a c t o r i a l (1) ) ; ASSERT EQ(24 , f a c t o r i a l (4) ) ; ASSERT EQ(120 , f a c t o r i a l (5) ) ; }
  • 17. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 18. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Why ? Portable: Works for Windows, Linux and Mac Familiar: Similar to other xUnit frameworks (JUnit, PyUnit, etc.) Simple: Unit tests are small and easy to read Popular: Many users and available documentation Powerful: Allows advanced configuration if needed
  • 19. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Tests TEST ( ) macro defines a test name and function TEST( test case name , test name ) { . . . t e s t body . . . } Example: TEST( FibonacciTest , CalculateSeedValues ) { ASSERT EQ(0 , Fibonacci (0) ) ; ASSERT EQ(1 , Fibonacci (1) ) ; }
  • 20. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Assertions Checks expected behavior for function or method ASSERT * fatal failures (test is interrupted) EXPECT * non-fatal failures Operator <<custom failure message ASSERT EQ( x . s i z e () , y . s i z e () ) << ” Vectors x and y are of unequal l ength ” ; f o r ( i n t i = 0; i < x . s i z e () ; ++i ) { EXPECT EQ( x [ i ] , y [ i ] ) << ” Vectors x and y d i f f e r at index ” << i ; }
  • 21. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Assertions Logic assertions Description Fatal assertion Non-fatal assertion True condition ASSERT TRUE(condition); EXPECT TRUE(condition); False condition ASSERT FALSE(condition); EXPECT FALSE(condition); Integer assertions Description Fatal assertion Non-fatal assertion Equal ASSERT EQ(expected, actual); EXPECT EQ(expected, actual); Less then ASSERT LT(expected, actual); EXPECT LT(expected, actual); Less or equal then ASSERT LE(expected, actual); EXPECT LE(expected, actual); Greater then ASSERT GT(expected, actual); EXPECT GT(expected, actual); Greater or equal then ASSERT GE(expected, actual); EXPECT GE(expected, actual);
  • 22. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Assertions String assertions Description Fatal assertion Non-fatal assertion Different content ASSERT STRNE(exp, actual); EXPECT STREQ(exp, actual); Same content, ig- noring case ASSERT STRCASEEQ(exp,actual); EXPECT STRCASEEQ(exp,actual); Different content, ignoring case ASSERT STRCASENE(exp,actual); EXPECT STRCASEEQ(exp,actual); Explicit assertions Description Assertion Explicit success SUCCEED(); Explicit fatal failure FAIL(); Explicit non-fatal failure ADD FAILURE(); Explicit non-fatal failure with detailed message ADD FAILURE AT(”file path”,linenumber);
  • 23. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Assertions Exception assertions Description Fatal assertion Non-fatal assertion Exception type was thrown ASSERT THROW(statement,exception); EXPECT THROW(statement, exception); Any exception was thrown ASSERT ANY THROW(statement); EXPECT ANY THROW(statement); No exception thrown ASSERT NO THROW(statement); EXPECT NO THROW(statement); Floating point number assertions Description Fatal assertion Non-fatal assertion Double compari- son ASSERT DOUBLE EQ(expected, actual); EXPECT DOUBLE EQ(expected, actual); Float comparison ASSERT FLOAT EQ(expected, actual); EXPECT FLOAT EQ(expected, actual); Float point com- parison with mar- gin of error ASSERT NEAR(val1, val2, abse rror); EXPECT NEAR(val1, val2, abse rror);
  • 24. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Test fixtures Definition: Tests that operate on similar data c l a s s LogTests : p u b l i c : : t e s t i n g : : Test { p r o t e c t e d : void SetUp () { . . . } // Prepare data f o r each t e s t void TearDown () { . . . } // Release data f o r each t e s t i n t auxMethod ( . . . ) { . . . } } TEST F ( LogTests , c l e a n L o g F i l e s ) { . . . t e s t body . . . }
  • 25. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Controlling execution Run all tests mytestprogram . exe Runs ”SoundTest” test cases mytestprogram . exe − g t e s t f i l t e r=SoundTest .∗ Runs tests whose name contains ”Null” or ”Constructor” mytestprogram . exe − g t e s t f i l t e r =∗Null ∗:∗ Constructor ∗ Runs tests except those whose preffix is ”DeathTest” mytestprogram . exe − g t e s t f i l t e r =−∗DeathTest .∗ Run ”FooTest” test cases except ”testCase3” mytestprogram . exe − g t e s t f i l t e r=FooTest.∗−FooTest . testCase3
  • 26. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Controlling execution Temporarily Disabling Tests For test cases, add DISABLED preffix TEST( SoundTest , DISABLED legacyProcedure ) { . . . } For all tests cases in test fixture, add DISABLED to test fixture name c l a s s DISABLED VectTest : p u b l i c : : t e s t i n g : : Test { . . . }; TEST F ( DISABLED ArrayTest , testCase4 ) { . . . } Enabling execution of disabled tests mytest . exe −−g t e s t a l s o r u n d i s a b l e d t e s t s
  • 27. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Output customization Invoking tests with output customization mytest program . exe −−g t e s t o u t p u t =”xml : d i r e c t o r y m y f i l e . xml” XML format (JUnit compatible) <t e s t s u i t e s name=” A l l T e s t s ” . . .> <t e s t s u i t e name=” test case name ” . . .> <t e s t c a s e name=” test name ” . . .> <f a i l u r e message=” . . . ”/> <f a i l u r e message=” . . . ”/> <f a i l u r e message=” . . . ”/> </ t e s t c a s e> </ t e s t s u i t e> </ t e s t s u i t e s>
  • 28. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Output customization Listing test names (without executing them) mytest program . exe −−g t e s t l i s t t e s t s TestCase1 . TestName1 TestName2 TestCase2 . TestName
  • 29. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Advanced features Predicate assertions AssertionResult Predicate formatter Windows HRESULT assertions Type assertions Customizing value type serialization Death tests Logging additional information in XML output Value parametized tests Etc ...
  • 30. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 31. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Types of functions Testing functions From testing perspective, there are mainly 3 types of functions: functions with input and output. Ex: math functions functions with input and object side-effect. Ex: person.setName(’John’); functions with input and not testable side-effect. Ex: drawLine(30,30,120,190);
  • 32. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Types of functions Functions with input and output the easiest case - direct implementation functions should be refactored to this format when possible TEST( FibonacciTest , FibonacciOfZeroShouldBeZero ) { ASSERT EQ(0 , f i b o n a c c i (0) ) ; } TEST( FibonacciTest , FibonacciOfOneShouldBeOne ) { ASSERT EQ(1 , f i b o n a c c i (1) ) ; } TEST( FibonacciTest , F i b o n a c c i O f S m a l l P o s i t i v e I n t e g e r s ) { ASSERT EQ(2 , f i b o n a c c i (3) ) ; ASSERT EQ(3 , f i b o n a c c i (4) ) ; }
  • 33. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Types of functions Functions with input and object side-effect not so direct but still easy object should contain a read method to check state TEST( PersonTest , SetBirthDateShouldModifyAge ) { Person p ; p . setBirthDate ( ”1978−09−16” ) ; ASSERT STR EQ(36 , p . age () ) ; }
  • 34. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Types of functions Functions with input and not testable side-effect can’t test what we can’t measure (in code) effort is not worth for unit testing TEST( DisplayTest , LineShouldBeDisplayed ) { Display d i s p l a y ; d i s p l a y . drawLine (20 ,34 ,100 ,250) ; ??????????? − How to a s s e r t t h i s ??? }
  • 35. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Configuration and implementation Isolate configuration from the actual code How to test Init failure in this code ? c l a s s Component { p u b l i c : i n t i n i t () { i f ( XYZ License ( ” key abcdefg ” ) != 0) { r e t u r n INIT FAILURE ; } r e t u r n INIT SUCCESS ; } }; ’init’ is a function without testable side-effects
  • 36. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Configuration and implementation Isolate configuration from the actual code Instead separate configuration from code c l a s s Component { p r o t e c t e d : std : : s t r i n g l i c e n s e = ” key abcdefg ” ; p u b l i c : i n t i n i t () { i f ( XYZ License ( l i c e n s e ) == FAILURE) { r e t u r n INIT FAILURE ; } } }; License information became an object variable
  • 37. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Configuration and implementation Isolate configuration from the actual code Extend class to add methods to access protected information c l a s s TestableComponent : p u b l i c Component { p u b l i c : void s e t L i c e n s e ( s t r i n g l i c e n s e ) { t h i s . l i c e n s e = l i c e n s e ; } }; ’setLicense’ is necessary to modify the state of ’init’ method
  • 38. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Configuration and implementation Isolate configuration from the actual code Now the test becomes possible: TEST( ComponentTest , U p o n I n i t i a l i z a t i o n F a i l u r e S h o u l d Return ErrorCode ) { // A u x i l i a r t e s t c l a s s can be d e c l a r e d only // i n the scope of the t e s t c l a s s TestableComponent : p u b l i c Component { p u b l i c : void s e t L i c e n s e ( s t r i n g l i c e n s e ) { t h i s . l i c e n s e = l i c e n s e ; } }; TestableComponent component ; component . s e t L i c e n s e ( ”FAKE LICENSE” ) ; ASSERT EQ( INIT FAILURE , component . i n i t () ) ; };
  • 39. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Extract your application Separate app logic from presentation Presentation logic refers to UI components to show user feedback Application logic refers to data transformation upon user or other system input Presentation and logic should be separated concerns Presentation is usually not unit testable Application logic is usually testable std : : s t r i n g name = u i . txtName . t e x t () ; std : : s i z e t p o s i t i o n = name . f i n d ( ” ” ) ; std : : s t r i n g firstName = name . s u b s t r (0 , p o s i t i o n ) ; std : : s t r i n g lastName = name . s u b s t r ( p o s i t i o n ) ; u i . l b D e s c r i p t i o n . setText ( lastName + ” , ” + firstName ) ;
  • 40. What is a unit test? How to get started ? GTest - basics Make code testable General tips References Extract your application Separate app logic from presentation Extract app logic in a separated function (preferrebly class) std : : s t r i n g name = u i . txtName . t e x t () ; std : : s t r i n g d e s c r i p t i o n = app . makeDescription (name) ; u i . l b D e s c r i p t i o n . setText ( d e s c r i p t i o n ) ; TEST( ApplicationTest , shouldMakeDescription ) { A p p l i c a t i o n app ; std : : s t r i n g d e s c r i p t i o n ; d e s c r i p t i o n = app . makeDescription ( ”James O l i v e r ” ) ; ASSERT STREQ( ” Oliver , James” , d e s c r i p t i o n ) ; }
  • 41. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Code with mixed responsibilities HttpResponse response ; response = http . get ( ” http :// domain/ api / contry code ” + ”? token=” + token ) ; std : : s t r i n g countryCode = response . body ; std : : s t r i n g langCode ; i f ( countryCode == BRAZIL) { langCode = PORTUGUESE; } e l s e i f ( countryCode == USA) { langCode = ENGLISH ; } e l s e { langCode = ENGLISH ; } u i . setLanguage ( langCode ) ;
  • 42. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Identify and isolate dependency WebAPIGateway webAPI ; std : : s t r i n g countryCode=webAPI . userCountryCode ( token ) ; LanguageHelper language ; std : : s t r i n g langCode=language . findLang ( countryCode ) ; u i . setLanguage ( langCode ) ; TEST( LanguageHelperTest , shouldFindLanguageForCountry ) { LanguageHelper language ; ASSERT EQ(PORTUGUESE, language . findLang (BRAZIL) ) ; ASSERT EQ(ENGLISH , language . findLang (USA) ) ; ASSERT EQ(ENGLISH , language . findLang (JAPAN) ) ; . . . }
  • 43. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Fake objects #i n c l u d e ”gmock/gmock . h” TEST( WebAPIGatewayTest , shouldFindUserCountry ) { c l a s s HttpRequestFake : p u b l i c HttpRequest { std : : s t r i n g userCountryCode ( std : : s t r i n g token ) { std : : s t r i n g country = ”” ; i f ( token==”abc” ) country = BRAZIL ; r e t u r n country ; } }; HttpRequest ∗ httpFake = new HttpRequestFake () ; WebAPIGateway api = WebAPIGateway ( httpFake ) ; std : : s t r i n g countryCode = api . userCountryCode ( ”abc” ) ; d e l e t e httpFake ; ASSERT EQ(BRAZIL , countryCode ) ; }
  • 44. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Mock objects #i n c l u d e ”gmock/gmock . h” c l a s s HttpRequestMock : p u b l i c HttpRequest { MOCK CONST METHOD1( get () , std : : s t r i n g ( std : : s t r i n g ) ) ; }; TEST( WebAPIGatewayTest , shouldFindUserCountry ) { HttpRequest ∗ httpMock = new HttpRequestMock () ; WebAPIGateway api = WebAPIGateway ( httpMock ) ; EXPECT CALL( httpMock , get ( ” http :// domain/ api / contry code ? token=abc” ) . Times (1) . WillOnce ( Return ( Response (BRAZIL) ) ) ; std : : s t r i n g countryCode = api . userCountryCode ( ”abc” ) ; d e l e t e httpMock ; ASSERT EQ(BRAZIL , countryCode ) ; }
  • 45. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Code with dependencies How to test vertices coordinates calculation ? void drawQuad ( f l o a t cx , f l o a t cy , f l o a t s i d e ) { f l o a t h a l f S i d e = s i d e / 2 . 0 ; glBegin (GL LINE LOOP) ; g l V e r t e x 3 f ( cx−h a l f S i d e , cy−h a l f S i d e ) ; g l V e r t e x 3 f ( cx+h a l f S i d e , cy−h a l f S i d e ) ; g l V e r t e x 3 f ( cx+h a l f S i d e , cy+h a l f S i d e ) ; g l V e r t e x 3 f ( cx−h a l f S i d e , cy+h a l f S i d e ) ; glEnd () ; }
  • 46. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Identify and isolate dependency void drawQuad ( f l o a t cx , f l o a t cy , f l o a t side , I D i s p l a y ∗ d i s p l a y { f l o a t h a l f S i d e = s i d e / 2 . 0 ; std : : vector <f l o a t > v e r t i c e s = { cx−h a l f S i d e , cy−h a l f S i d e , cx+h a l f S i d e , cy−h a l f S i d e , cx+h a l f S i d e , cy+h a l f S i d e , cx−h a l f S i d e , cy+h a l f S i d e }; d i s p l a y −>r e c t a n g l e ( v e r t i c e s ) ; } c l a s s Display : p u b l i c I D i s p l a y { p u b l i c : void r e c t a n g l e ( std : : vector <f l o a t > v e r t i c e s ) { glBegin (GL LINE LOOP) ; g l V e r t e x 3 f ( v e r t i c e s [ 0 ] , v e r t i c e s [ 1 ] ) ; . . . glEnd () ; } };
  • 47. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Fake objects TEST( DrawTests , drawQuadShouldCalculateVertices ) { c l a s s FakeDisplay : p u b l i c Display { p r o t e c t e d : std : : vector <f l o a t > v e r t i c e s ; p u b l i c : void r e c t a n g l e ( std : : vector <f l o a t > v e r t i c e s ) { v e r t i c e s = v e r t i c e s ; } std : : vector <f l o a t > v e r t i c e s () { r e t u r n v e r t i c e s ; } }; I D i s p l a y ∗ d i s p l a y = new FakeDisplay () ; drawQuad ( 1 0 . 0 , 1 0 . 0 , 1 0 . 0 , d i s p l a y ) ; ASSERT VECT EQ( { 5 . 0 , 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 } , d i s p l a y −>v e r t i c e s () ) ; }
  • 48. What is a unit test? How to get started ? GTest - basics Make code testable General tips References External dependencies Mock objects #i n c l u d e ”gmock/gmock . h” TEST( DrawTests , drawQuadShouldCalculateVertices ) { c l a s s MockDisplay : p u b l i c Display { MOCK METHOD1( r e c t a n g l e , void ( std : : vector <f l o a t >) ; }; I D i s p l a y ∗ d i s p l a y = new MockDisplay () ; EXPECT CALL( d i s p l a y , r e c t a n g l e ( { 5 . 0 , 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 , 1 5 . 0 , 5 . 0 , 1 5 . 0 } ) . Times (1) drawQuad ( 1 0 . 0 , 1 0 . 0 , 1 0 . 0 , d i s p l a y ) ; }
  • 49. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 50. What is a unit test? How to get started ? GTest - basics Make code testable General tips References General tips Test behavior not implementation There is no behavior in non-public methods Use name convention for tests to improve readability Test code should be as good as production code - it is not sketch code GTest alone can’t help you Workflow is important - talk to your QA Improve modularization to avoid being trapped by non testable code Use mock objects with caution Understand the difference between fake and mock objects
  • 51. What is a unit test? How to get started ? GTest - basics Make code testable General tips References 1 What is a unit test? 2 How to get started ? 3 GTest - basics Why ? Tests Assertions Test fixtures Controlling execution Output customization Advanced features 4 Make code testable Types of functions Configuration and implementation Extract your application External dependencies 5 General tips 6 References
  • 52. What is a unit test? How to get started ? GTest - basics Make code testable General tips References General tips Getting Started with Google Testing Framework https://code.google.com/p/googletest/wiki/Primer GTest Advanced Guide https://code.google.com/p/googletest/wiki/AdvancedGuide Clean Code: A Handbook of Agile Software Craftsmanship Robert C. Martin - Prentice Hall PTR, 2009 Google C++ Mocking Framework for Dummies https://code.google.com/p/googlemock/wiki/ForDummies