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

Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
[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
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Mutation Testing
Mutation TestingMutation Testing
Mutation TestingESUG
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentguestc8093a6
 
Test unitaire
Test unitaireTest unitaire
Test unitaireIsenDev
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Writing Test Cases in Agile
Writing Test Cases in AgileWriting Test Cases in Agile
Writing Test Cases in AgileSaroj Singh
 

What's hot (20)

Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
[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
 
Nunit
NunitNunit
Nunit
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Mutation Testing
Mutation TestingMutation Testing
Mutation Testing
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Junit
JunitJunit
Junit
 
Test unitaire
Test unitaireTest unitaire
Test unitaire
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Writing Test Cases in Agile
Writing Test Cases in AgileWriting Test Cases in Agile
Writing Test Cases in Agile
 
Code coverage
Code coverageCode coverage
Code coverage
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
 

Similar to C++ Unit Test with Google Testing Framework

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
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetdevlabsalliance
 

Similar to C++ Unit Test with Google Testing Framework (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
 
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
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdet
 

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

%+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
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
%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
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 

Recently uploaded (20)

%+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...
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%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
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

C++ Unit Test with Google Testing Framework

  • 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