Pages

Tuesday, June 21, 2011

Using Google C++ Test Framework with Visual Studio 2008

I recently needed to add a testing framework to a Visual Studio 2008 C++ project and I stumbled on Google's C+ Testing Framework. A lot of people seemed to be happy with it and I figured I'd give it a try, if it's written by Google it can't be bad :) ^_^!

It's been a couple of years since I've done any C++ testing and as always: StackOverflow had the answer for me. The guide is for Visual Studio 2005, but it works just as good with Visual Studio 2008. I was even able to get it all to build and run in 64 bit mode, so I was a pretty happy camper!

Here are the instructions that worked for me with some minor modifications (verbatim from nonsensical101's SO answer):

(These instructions get the testing framework working for the Debug configuration. It should be pretty trivial to apply the same process to the Release configuration.)

Get Google C++ Testing Framework

Download the latest gtest framework
Unzip to C:\gtest

Build the Framework Libraries

Open C:\gtest\msvc\gtest.sln in Visual Studio
Set Configuration to "Debug"
Build Solution

Create and Configure Your Test Project

Create a new solution and choose the template Visual C++ > Win32 > Win32 Console Application
** If you choose to create an empty project, you will not have Stdafx.h (you may not actually need it anyway).
Right click the newly created project and choose Properties
Change Configuration to Debug.
Configuration Properties > C/C++ > General > Additional Include Directories: Add C:\gtest\include
Configuration Properties > C/C++ > Code Generation > Runtime Library: If your code links to a runtime DLL, choose Multi-threaded Debug DLL (/MDd). If not, choose Multi-threaded Debug (/MTd).
** Note that both your project and gtest have to be build with the same Code Generation options: i.e. both have to be /MDd or /MTd
Configuration Properties > Linker > General > Additional Library Directories: Add C:\gtest\msvc\gtest\Debug
Configuration Properties > Linker > Input > Additional Dependencies: Add gtestd.lib

Verifying Everything Works

Open the cpp in your Test Project containing the main() function.
Paste the following code:


// #include "stdafx.h" // <-- I didn't need stdafx.h
#include

#include "gtest/gtest.h"

TEST(sample_test_case, sample_test)
{
EXPECT_EQ(1, 1);
}

int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
RUN_ALL_TESTS();
std::getchar(); // keep console window open until Return keystroke
}

Debug > Start Debugging

If everything worked, you should see the console window appear and show you the unit test results.



Indeed, everything worked and I was able to see the test results. As I mentioned in my comments: make sure that you compile both the testing framework and the test project with the same output options and everything should go without a hitch. Now I'm off to testing some C++ code, woohoo!