Unit testing is critical for quality code – they help you:
- find problems early
- facilitate change by avoiding breakage of other functionality
- simplify integration via a bottom up approach
- document the code
- maintain good design – testable code is good code: single intent, clear retval etc
Google has created a unit testing framework for C++ :
http://code.google.com/p/googletest/
I downloaded Google Test from http://code.google.com/p/googletest/downloads/list and built the solution under the msvc folder (Im using Visual C++ today). I see that there is a lib file created here called gtest-1.6.0\msvc\gtest\Debug\gtestd.lib
I then created a new VC++ Win32 Console App and set the following project properties:
VC++ Directories > Include Directories – added path to ..\ gtest-1.6.0\include
VC++ Directories > Library Directories – added path to ..\ gtest-1.6.0\msvc\gtest\Debug
Linker > Input > Additional Dependencies - added gtestd.lib
All swell ?
I thought so, until I compiled & got the dreaded LNK2005: http://msdn.microsoft.com/en-us/library/72zdcz6f(v=vs.80).aspx
WTF – linker errors ?
To quote Cousin Eddie from National Lampoon’s Vacation:
'Everytime Catherine would turn in the microwave I'd piss my pants and forget my name' - C++ often makes me feel like an idiot !
Thank God for Pavel http://blogs.microsoft.co.il/blogs/pavely/ , who pointed out to me that I need to change the C runtime library from DLL multithreaded debug to multithreaded debug:
![clip_image002[5] clip_image002[5]](http://gwb.blob.core.windows.net/joshreuben/Windows-Live-Writer/C-Unit-Testing-with-GoogleTest_A85A/clip_image0025_thumb.gif)
I could now build.
I added an include to access the Google Test macros:
#include "gtest/gtest.h"
I then created a canonical testable function:
int Factorial(int x, int result = 1) {
if (x == 1) return result;
else return Factorial(x - 1, x * result);
}
I used the TEST macro to construct a named test – it leveraged the EXPECT_EQ & EXPECT_GT macros to test for equality and greater than respectably.
TEST(FactorialTest, Negative) {
EXPECT_EQ(1, Factorial(-1));
EXPECT_GT(Factorial(-10), 0);
}
in my main function, I initialized google test & used RUN_ALL_TESTS macro to … run all tests.
int _tmain(int argc, _TCHAR* argv[])
{
testing::InitGoogleTest(&argc,argv);
RUN_ALL_TESTS();
int x;
std::cin >> x;
return 0;
}
I debugged my code - It breaks into the test:

And I get the following test results displayed:

So I am up & running with C++ Google Test !
Further things to try:
All fun & games !