Testing C++ Code with Google Test

Object-oriented design in C++ with Kristoffer Hebert

Kristoffer Hebert
Dec 17, 2018 · 2 min read

Overview

Google test is a unit testing framework for C++. It uses boolean values to test C++ code. The two tests are ASSERT and EXPECT. Use ASSERT when you want to the test runner to stop if a test fails.

File Layout

lib
main.cpp
fibonacci.cpp
fibonacci.h
test/main.cpp
build.sh

Lib is a folder for installing packages like Google Test. I had a hard time installing in for OSX, but this article helped me.

The main.cpp contains an application that lists the Fibonacci numbers from 1 to 20. It pulls the code for the function from fibonacci.cpp and fibonacci.h defines the arguments for that function.

The test folder that contains all of the Google test unit tests and compiled test executable.

Build.sh contains the code to compile the C++ test and applications.

// build.sh
g++ -std=c++11 main.cpp fibonacci.cpp -o ./main
g++ -std=c++11 test/main.cpp fibonacci.cpp -lgtest -o test/test

Code

fibonacci files

Tests

tests/main.cpp

Executing Tests

// Compile files
./build.sh
// Run Tests
./test/test
// Results[==========] Running 1 test from 1 test case.
[ — — — — — ] Global test environment set-up.
[ — — — — — ] 1 test from TestFibonacci
[ RUN ] TestFibonacci.TestFunctionResults
[ OK ] TestFibonacci.TestFunctionResults (0 ms)
[ — — — — — ] 1 test from TestFibonacci (0 ms total)
[ — — — — — ] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 1 test.

Useful Google Test functions

// ASSERT_TRUE
// Should be a true value
ASSERT_TRUE(fibonacci(1) == 1);
// EXPECT_EQ
// Expect two values to match.
EXPECT_EQ (fibonacci(1), 1);
Kristoffer Hebert

Written by

I am working toward a simpler, more meaningful world. kristofferhebert.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade