SlideShare a Scribd company logo
1 of 40
Download to read offline
An Introduction to Google Test
Framework
Abner Huang
July. 2015
Test!? We do it every day
void Test__calc_isect() {
int x1, y1, x2, y2;
int x3, y3, x4, y4;
int x, y;
x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX;
x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN;
calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0);
assert(x == 11);
assert(y == INT_MAX);
}
void main(void)
{
Test__calc_isect1();
Test__calc_isect2();
Test__calc_isect3();
Test__calc_isect();
Test__calc_isect4();
Test__calc_isect5();
Test__calc_isect6();
}
> ./test.out
test.cpp:100:Test__calc_isect(): Assertion `x == 11' failed.
void Test__calc_isect() {
int x1, y1, x2, y2;
int x3, y3, x4, y4;
int x, y;
x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX;
x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN;
calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0);
if ((x != 11) || (y != INT_MAX))
{
printf(“Oops! (%d,%d) != (%d,%d)n”,x,y,11,INT_MAX);
assert(0);
}
printf(“PASSn”);
}
> ./test.out
PASS
PASS
PASS
Oops! (10,2147483647) != (11,2147483647)
test.cpp:100:Test__calc_isect(): Assertion `0' failed.
Any complains?
No convenient controls
Run in batch mode
Does gtest help?
No control of test suite
and test cases
./your_test.out --help
● Selecting Tests
● Repeating/Shuffling the Tests
● Generating an XML Report
● Turning Assertion Failures into Break-Points
○ --gtest_break_on_failure
● Disabling Catching Test-Thrown Exceptions
○ --gtest_catch_exceptions=0
> libpl_test --gtest_list_tests
CHK_ENCLOSE.
PlEnclose_SimpleInput
MAKE_BD.
MakeBd_LineTouchDirty
OSIZE_HDR.
OversizeHdr_BadOversizAmount
OversizeHdr_NULLInput
OversizeHdr_SimpleInput
OversizeHdr_OversizeOrthoHdr
OversizeHdr_OversizeNonOrthoHdr
OversizeOrthoHdr_OversizeOrthoHdr
BreakUpAngleHdr_DisconnectedInput
BreakUpAngleHdr_AngleBigInput
https://www.flickr.com/photos/marckjerland/4285433177 On Flickr, marc kjerland's Mathematician's toolkit
● Fatal and non-fatal assertions
○ EXPECT_EQ(x, 10);EXPECT_FLOAT_EQ(x,10.0)
○ ASSERT_EQ(x, 10);ASSERT_DOUBLE_EQ(x,10.0)
● Easy assertions informative messages:
assert(x == 10);
EXPECT_EQ(x, 10) << “vector (” << old_x <<
”,” << old_y << ”) moved to (” << x << ”,” <<
y << ”)n”;
> ./test.out
[ RUN ] MYTEST.TestFoo
test.cpp:37: Failure
Value of: x
Actual: 11
Expected: 10
vector (10, 77) move to (11, 77)
[ FAILED ] MYTEST.TestFoo (0 ms)
DEATH TEST
calc_isect(int *x, int *y, int x1, int y1, int x2, int y2,
int x3, int y3, int x4, int y4, int tolerance)
{
if (x==NULL || y==NULL)
{
cerr << “Input is invalid.n”;
exit(1);
}
… …
}
TEST(GEODeathTest, CalcIsect) {
ASSERT_DEATH(CalcIsect(NULL, NULL, 0,0,0,0,0,0,0,0,0),
".*invalid");
}
Adding Traces to Assertions
void Sub1(int n) {
EXPECT_EQ(1, Bar(n));
EXPECT_EQ(2, Bar(n + 1));
}
TEST(FooTest, Bar) {
{
SCOPED_TRACE("A");
Sub1(1);
}
Sub1(9);
}
path/to/foo_test.cc:11: Failure
Value of: Bar(n)
Expected: 1
Actual: 2
Trace:
path/to/foo_test.cc:17: A
path/to/foo_test.cc:12: Failure
Value of: Bar(n + 1)
Expected: 2
XML outputs
<testsuites name="AllTests" tests="3" failures="
1" errors="0" time="35" ...>
<testsuite name="test_case_name" tests="2"
failures="1" errors="0" time="15"...>
<testcase name="test_name" status="run"
time="7"...>
<failure message="..."/>
<failure message="..."/>
</testcase>
</testsuite>
</testsuites>
Prepare your test case
• test.cpp contains main() in test directory
#include "_test_util.h"
static void
infrastructure_init(void)
{
vmemUseMalloc(1);
vmemInit_m();
vmemSetIncrementValue(VMEM_MEGABYTE_MINUS);
hoVMsetDefaultPoolLockingState(0);
vth_init();
}
int main(int argc, char **argv) {
infrastructure_init(); // Write a function like this to initialize vmem, threading etc.
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS(); Initialize gtest and runs all tests.
return result;
}
SetUp()
TEST/TEST_F/TEST_PTearDown()
Test types of Gtest
• TEST()
• TEST_F() -- Fixture
• TEST_P() -- Value-parameterized fixture
– Range()
– Values()
– ValuesIn()
– Bool()
– Combine()
TEST(GEO, CalcIsect) {
int x1, y1, x2, y2;
int x3, y3, x4, y4;
int x, y;
x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX;
x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN;
calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0);
assert(x == 11);
assert(y == INT_MAX);
}
Test Fixtures
• Sometimes you want to run several tests on similar data
structures (same setup before running test).
• In a fixture you define common setup/tear-down for
multiple tests
• Reduces amount of test code by avoiding repetition
class GEO : public ::testing::Test {
protected:
virtual void SetUp() {}
void ZapMemoryPool() {}
virtual void TearDown() {}
int x1, y1, x2, y2, x3, y3, x4, y4, x, y;
};
TEST_F(GEO, CalcIsect) {
x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX;
x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN;
calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0);
assert(x == 11);
assert(y == INT_MAX);
}
TEST_P() -- Value-parameterized fixture
● generator based tests.
Range(begin, end[,
step])
Yields values {begin, begin+step, begin+step+step, ...}. The values do
not include end. step defaults to 1.
Values(v1, v2, ..., vN) Yields values {v1, v2, ..., vN}.
ValuesIn(container) and
ValuesIn(begin, end)
Yields values from a C-style array, an STL-style container, or an
iterator range [begin, end). container, begin, and end can be
expressions whose values are determined at run time.
Bool() Yields sequence {false, true}.
Combine(g1, g2, ...,
gN)
Yields all combinations (the Cartesian product for the math savvy) of
the values generated by the N generators. This is only available if your
system provides the <tr1/tuple> header.
class GEO : public ::testing::TestWithParam<int> {
protected:
virtual void SetUp() {}
void ZapMemoryPool() {}
virtual void TearDown() {}
int x1, y1, x2, y2, x3, y3, x4, y4, x, y;
};
INSTANTIATE_TEST_CASE_P(AUTO_GEN_OH, GEO, ::testing::Range(1,12,1));
TEST_P(GEO, CalcIsect) {
double angle = PI/180 * 15 * GetParam();
x1 = -100; y1 = 0; x2 = 100; y2 = 0;
x3 = -50; y3 = 0; x4 = 50; y4 = 0;
rotate(&x3, &y4, angle);
rotate(&x4, &y4, angle);
calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0);
assert(x == 0 && y == 0);
}
[----------] 16 tests from AUTO_GEN_OH/GEO
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/1
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/1 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/2
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/2 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/3
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/3 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/4
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/4 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/5
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/5 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/6
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/6 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/7
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/7 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/8
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/8 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/9
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/9 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/10
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/10 (0 ms)
[ RUN ] AUTO_GEN_OH/GEO.CalcIsect/11
[ OK ] AUTO_GEN_OH/GEO.CalcIsect/11 (0 ms)
[----------] 11 tests from AUTO_GEN_OH/GEO (0 ms total)
Organization of Tests
TEST(GEO, CalcIsect)
test case test
Test Suite
Flow of Running Tests
SetUp()
TEST/TEST_F/TEST_PTearDown()
Environment::
SetUp()
SetUpTestCase()
Environment::
TearDown()
TearDownTestCase()
How to install gtest
Easy Install
> wget http://googletest.googlecode.com/files/gtest-1.7.0.zip
> unzip gtest-1.7.0.zip
> cd gtest-1.7.0
> ./configure
> make
> cp -a include/gtest /usr/include
> sudo cp -a lib/.libs/* /usr/lib/
How to use google test
• You must check out gtest to use unit test feature. We do
not have the executable of gtest.
• E.g.
– /path/to/foo/
– build
– arch
– src
– exec
– gtest
– include
– lib
How to use google test (II)
• E.g.
/path/to/foo/
– exec
– gtest
– include
– lib
– bar <<< Library under test, contains production code
– published
– test <<< Directory contains test code
test> make
Some points to keep in mind
• gtest is useful for testing primitive functions in libraries
• Unit testing does not replace regression testing
• With gtest:
– You do not modify production code.
– You add test code that calls library functions.
– You check-in test code to repository
• Production code is not compiled/linked with gtest
• Using gtest creates a test binary, not icv binary
Coding Style and Rules
• Don’t mix TEST(), TEST_F(), TEST_P()
• Don’t use global variables, use test fixture to instead
• Gtest does not reuse the same test fixture object across
multiple tests
• Spell SetUp() correctly.
• Gtest use fork() to do death test, do not try not to free
memory in a death test.
• You can derive new class from your own class.
Coding Style and Rules
• Use Camel Case style to name test cases and suite
– E.g., TEST(Time, Flies_Like_An_Arrow) { ... }
and
TEST(Time_Flies, Like_An_Arrow) { … }
will have the same name
Time_Files_Like_An_Arrow_Test
• Current Naming Rule
– Test suite name is all uppercase
– Test case name is Camel Case style with underscore.
– E.g., TEST_F(SPACING_UTIL__PNT_EDGE, WhichHalfRes_SamePoints)
Key Features & Characters Boost Test Google Test UnitTest++
Free (Open Source) software Yes Yes Yes
Simple to use Yes
(5 out of 5)
Yes
(5 out of 5)
Yes
(4 out of 5)
Test cases grouping & organization Good Good Normal
Test case template support Yes Yes Yes
Test fixture (i.e. fixed state used as
a baseline for running test) support
Yes Yes Yes
Global test fixture Yes Yes No
Handle C++ exceptions Yes Yes Yes
Different types of assertions support Yes Yes No
Fatal and non-fatal assertions Yes Yes No
Support Regular Expression when
matching function output
Yes Yes No
Output in XML format Yes Yes No
Key Features & Characters Boost Test Google Test UnitTest++
Support Mock object (objects can
simulate the behavior of complex
objects)
No Yes
(work seamlessly with
Google Mock)
No
Extend features with event
mechanism
No Yes No
Run tests on distributed machines No Yes No
Thread safety when running tests No Yes No
Run subset of all defined test cases Yes
(only support
filtering by test
name)
Yes
(support multiple
filtering conditions)
No
• Karl Chen, C++ Unit Testing Frameworks Evaluation
Thank you

More Related Content

What's hot (20)

Junit
JunitJunit
Junit
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
구글테스트
구글테스트구글테스트
구글테스트
 
Clean code
Clean codeClean code
Clean code
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
[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
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 

Similar to An introduction to Google test framework

Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaRobot Media
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean testsDanylenko Max
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4jeresig
 
Yoyak ScalaDays 2015
Yoyak ScalaDays 2015Yoyak ScalaDays 2015
Yoyak ScalaDays 2015ihji
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 
Ruslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingRuslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingIevgenii Katsan
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingPathomchon Sriwilairit
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingKevlin Henney
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxpriestmanmable
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfRahul04August
 
YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx
 YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx
YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docxgertrudebellgrove
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in GolangDan Tran
 

Similar to An introduction to Google test framework (20)

Unit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon GaliciaUnit testing en iOS @ MobileCon Galicia
Unit testing en iOS @ MobileCon Galicia
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Eta
EtaEta
Eta
 
Yoyak ScalaDays 2015
Yoyak ScalaDays 2015Yoyak ScalaDays 2015
Yoyak ScalaDays 2015
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Ruslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingRuslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testing
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit Testing
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx
 YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx
YOU SHOULD NOT MODIFY ANYTHING IN THIS FILE .docx
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in Golang
 

More from Abner Chih Yi Huang

諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式Abner Chih Yi Huang
 
Introduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemmaIntroduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemmaAbner Chih Yi Huang
 
Introduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market EqulibraIntroduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market EqulibraAbner Chih Yi Huang
 
More on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomizationMore on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomizationAbner Chih Yi Huang
 
A small debate of power of randomness
A small debate of power of randomnessA small debate of power of randomness
A small debate of power of randomnessAbner Chih Yi Huang
 
Dominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graphDominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graphAbner Chih Yi Huang
 
Introduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theoryIntroduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theoryAbner Chih Yi Huang
 

More from Abner Chih Yi Huang (11)

諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式諾貝爾經濟學獎得主的獲利公式
諾貝爾經濟學獎得主的獲利公式
 
Clip Tree Applications
Clip Tree ApplicationsClip Tree Applications
Clip Tree Applications
 
Introduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemmaIntroduction to Szemerédi regularity lemma
Introduction to Szemerédi regularity lemma
 
Introduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market EqulibraIntroduction to Algorithmic aspect of Market Equlibra
Introduction to Algorithmic aspect of Market Equlibra
 
SaaS: Science as a Service
SaaS: Science as a Service SaaS: Science as a Service
SaaS: Science as a Service
 
More on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomizationMore on randomization semi-definite programming and derandomization
More on randomization semi-definite programming and derandomization
 
Alignment spaced seed
Alignment spaced seedAlignment spaced seed
Alignment spaced seed
 
A small debate of power of randomness
A small debate of power of randomnessA small debate of power of randomness
A small debate of power of randomness
 
Dominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graphDominating set of fixed size in degenerated graph
Dominating set of fixed size in degenerated graph
 
Introduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theoryIntroduction to algorithmic aspect of auction theory
Introduction to algorithmic aspect of auction theory
 
Refactoring Chapter11
Refactoring Chapter11Refactoring Chapter11
Refactoring Chapter11
 

Recently uploaded

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 

Recently uploaded (20)

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 

An introduction to Google test framework

  • 1. An Introduction to Google Test Framework Abner Huang July. 2015
  • 2. Test!? We do it every day
  • 3. void Test__calc_isect() { int x1, y1, x2, y2; int x3, y3, x4, y4; int x, y; x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX; x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN; calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0); assert(x == 11); assert(y == INT_MAX); }
  • 6. void Test__calc_isect() { int x1, y1, x2, y2; int x3, y3, x4, y4; int x, y; x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX; x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN; calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0); if ((x != 11) || (y != INT_MAX)) { printf(“Oops! (%d,%d) != (%d,%d)n”,x,y,11,INT_MAX); assert(0); } printf(“PASSn”); }
  • 7. > ./test.out PASS PASS PASS Oops! (10,2147483647) != (11,2147483647) test.cpp:100:Test__calc_isect(): Assertion `0' failed.
  • 10. Run in batch mode
  • 12. No control of test suite and test cases
  • 13. ./your_test.out --help ● Selecting Tests ● Repeating/Shuffling the Tests ● Generating an XML Report ● Turning Assertion Failures into Break-Points ○ --gtest_break_on_failure ● Disabling Catching Test-Thrown Exceptions ○ --gtest_catch_exceptions=0
  • 15. https://www.flickr.com/photos/marckjerland/4285433177 On Flickr, marc kjerland's Mathematician's toolkit
  • 16. ● Fatal and non-fatal assertions ○ EXPECT_EQ(x, 10);EXPECT_FLOAT_EQ(x,10.0) ○ ASSERT_EQ(x, 10);ASSERT_DOUBLE_EQ(x,10.0) ● Easy assertions informative messages: assert(x == 10); EXPECT_EQ(x, 10) << “vector (” << old_x << ”,” << old_y << ”) moved to (” << x << ”,” << y << ”)n”;
  • 17. > ./test.out [ RUN ] MYTEST.TestFoo test.cpp:37: Failure Value of: x Actual: 11 Expected: 10 vector (10, 77) move to (11, 77) [ FAILED ] MYTEST.TestFoo (0 ms)
  • 18. DEATH TEST calc_isect(int *x, int *y, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int tolerance) { if (x==NULL || y==NULL) { cerr << “Input is invalid.n”; exit(1); } … … } TEST(GEODeathTest, CalcIsect) { ASSERT_DEATH(CalcIsect(NULL, NULL, 0,0,0,0,0,0,0,0,0), ".*invalid"); }
  • 19. Adding Traces to Assertions void Sub1(int n) { EXPECT_EQ(1, Bar(n)); EXPECT_EQ(2, Bar(n + 1)); } TEST(FooTest, Bar) { { SCOPED_TRACE("A"); Sub1(1); } Sub1(9); } path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 Actual: 2 Trace: path/to/foo_test.cc:17: A path/to/foo_test.cc:12: Failure Value of: Bar(n + 1) Expected: 2
  • 20. XML outputs <testsuites name="AllTests" tests="3" failures=" 1" errors="0" time="35" ...> <testsuite name="test_case_name" tests="2" failures="1" errors="0" time="15"...> <testcase name="test_name" status="run" time="7"...> <failure message="..."/> <failure message="..."/> </testcase> </testsuite> </testsuites>
  • 21. Prepare your test case • test.cpp contains main() in test directory #include "_test_util.h" static void infrastructure_init(void) { vmemUseMalloc(1); vmemInit_m(); vmemSetIncrementValue(VMEM_MEGABYTE_MINUS); hoVMsetDefaultPoolLockingState(0); vth_init(); } int main(int argc, char **argv) { infrastructure_init(); // Write a function like this to initialize vmem, threading etc. ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); Initialize gtest and runs all tests. return result; }
  • 22. SetUp() TEST/TEST_F/TEST_PTearDown() Test types of Gtest • TEST() • TEST_F() -- Fixture • TEST_P() -- Value-parameterized fixture – Range() – Values() – ValuesIn() – Bool() – Combine()
  • 23. TEST(GEO, CalcIsect) { int x1, y1, x2, y2; int x3, y3, x4, y4; int x, y; x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX; x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN; calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0); assert(x == 11); assert(y == INT_MAX); }
  • 24. Test Fixtures • Sometimes you want to run several tests on similar data structures (same setup before running test). • In a fixture you define common setup/tear-down for multiple tests • Reduces amount of test code by avoiding repetition
  • 25. class GEO : public ::testing::Test { protected: virtual void SetUp() {} void ZapMemoryPool() {} virtual void TearDown() {} int x1, y1, x2, y2, x3, y3, x4, y4, x, y; }; TEST_F(GEO, CalcIsect) { x1 = 0; y1 = INT_MIN; x2 = 2; y2 = INT_MAX; x3 = 20; y3 = INT_MAX; x4 = 22; y4 = INT_MIN; calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0); assert(x == 11); assert(y == INT_MAX); }
  • 26. TEST_P() -- Value-parameterized fixture ● generator based tests. Range(begin, end[, step]) Yields values {begin, begin+step, begin+step+step, ...}. The values do not include end. step defaults to 1. Values(v1, v2, ..., vN) Yields values {v1, v2, ..., vN}. ValuesIn(container) and ValuesIn(begin, end) Yields values from a C-style array, an STL-style container, or an iterator range [begin, end). container, begin, and end can be expressions whose values are determined at run time. Bool() Yields sequence {false, true}. Combine(g1, g2, ..., gN) Yields all combinations (the Cartesian product for the math savvy) of the values generated by the N generators. This is only available if your system provides the <tr1/tuple> header.
  • 27. class GEO : public ::testing::TestWithParam<int> { protected: virtual void SetUp() {} void ZapMemoryPool() {} virtual void TearDown() {} int x1, y1, x2, y2, x3, y3, x4, y4, x, y; }; INSTANTIATE_TEST_CASE_P(AUTO_GEN_OH, GEO, ::testing::Range(1,12,1)); TEST_P(GEO, CalcIsect) { double angle = PI/180 * 15 * GetParam(); x1 = -100; y1 = 0; x2 = 100; y2 = 0; x3 = -50; y3 = 0; x4 = 50; y4 = 0; rotate(&x3, &y4, angle); rotate(&x4, &y4, angle); calc_isect(&x, &y, x1, y1, x2, y2, x3, y3, x4, y4, 0); assert(x == 0 && y == 0); }
  • 28. [----------] 16 tests from AUTO_GEN_OH/GEO [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/1 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/1 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/2 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/2 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/3 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/3 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/4 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/4 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/5 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/5 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/6 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/6 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/7 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/7 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/8 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/8 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/9 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/9 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/10 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/10 (0 ms) [ RUN ] AUTO_GEN_OH/GEO.CalcIsect/11 [ OK ] AUTO_GEN_OH/GEO.CalcIsect/11 (0 ms) [----------] 11 tests from AUTO_GEN_OH/GEO (0 ms total)
  • 29. Organization of Tests TEST(GEO, CalcIsect) test case test Test Suite
  • 30. Flow of Running Tests SetUp() TEST/TEST_F/TEST_PTearDown() Environment:: SetUp() SetUpTestCase() Environment:: TearDown() TearDownTestCase()
  • 31. How to install gtest
  • 32. Easy Install > wget http://googletest.googlecode.com/files/gtest-1.7.0.zip > unzip gtest-1.7.0.zip > cd gtest-1.7.0 > ./configure > make > cp -a include/gtest /usr/include > sudo cp -a lib/.libs/* /usr/lib/
  • 33. How to use google test • You must check out gtest to use unit test feature. We do not have the executable of gtest. • E.g. – /path/to/foo/ – build – arch – src – exec – gtest – include – lib
  • 34. How to use google test (II) • E.g. /path/to/foo/ – exec – gtest – include – lib – bar <<< Library under test, contains production code – published – test <<< Directory contains test code test> make
  • 35. Some points to keep in mind • gtest is useful for testing primitive functions in libraries • Unit testing does not replace regression testing • With gtest: – You do not modify production code. – You add test code that calls library functions. – You check-in test code to repository • Production code is not compiled/linked with gtest • Using gtest creates a test binary, not icv binary
  • 36. Coding Style and Rules • Don’t mix TEST(), TEST_F(), TEST_P() • Don’t use global variables, use test fixture to instead • Gtest does not reuse the same test fixture object across multiple tests • Spell SetUp() correctly. • Gtest use fork() to do death test, do not try not to free memory in a death test. • You can derive new class from your own class.
  • 37. Coding Style and Rules • Use Camel Case style to name test cases and suite – E.g., TEST(Time, Flies_Like_An_Arrow) { ... } and TEST(Time_Flies, Like_An_Arrow) { … } will have the same name Time_Files_Like_An_Arrow_Test • Current Naming Rule – Test suite name is all uppercase – Test case name is Camel Case style with underscore. – E.g., TEST_F(SPACING_UTIL__PNT_EDGE, WhichHalfRes_SamePoints)
  • 38. Key Features & Characters Boost Test Google Test UnitTest++ Free (Open Source) software Yes Yes Yes Simple to use Yes (5 out of 5) Yes (5 out of 5) Yes (4 out of 5) Test cases grouping & organization Good Good Normal Test case template support Yes Yes Yes Test fixture (i.e. fixed state used as a baseline for running test) support Yes Yes Yes Global test fixture Yes Yes No Handle C++ exceptions Yes Yes Yes Different types of assertions support Yes Yes No Fatal and non-fatal assertions Yes Yes No Support Regular Expression when matching function output Yes Yes No Output in XML format Yes Yes No
  • 39. Key Features & Characters Boost Test Google Test UnitTest++ Support Mock object (objects can simulate the behavior of complex objects) No Yes (work seamlessly with Google Mock) No Extend features with event mechanism No Yes No Run tests on distributed machines No Yes No Thread safety when running tests No Yes No Run subset of all defined test cases Yes (only support filtering by test name) Yes (support multiple filtering conditions) No • Karl Chen, C++ Unit Testing Frameworks Evaluation