GTest (aka Google Test) is a C++ testing framework.
1: Install GTest
The first step is to install GTest (Google Test). There are some specific methods to install it, depends on which operating system you use. Like, if you use macOS, you can use brew with commend brew install googletest
, or if you use Ubuntu, you can use apt by apt install libgtest-dev
.
Or you can use some more general method below, which is what I used.
git clone https://github.com/google/googletest
cd googletest
mkdir build
cd build
cmake ..
make
make install
2: A sample example
In this step, we create a file called gtest.cc
and copy the following code into it.
#include <gtest/gtest.h>
TEST(module_name, test_name) {
EXPECT_FALSE(false);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Run it through terminal using:
$ g++ -std=c++11 gtest.cc -lgtest -lpthread
A file named a.out
will be created, which is the same as compile other c++ programs, then execute it by:
$ .\a.out
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from module_name
[ RUN ] module_name.test_name
[ OK ] module_name.test_name (0 ms)
[----------] 1 test from module_name (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
3. Another example
Let’s write a real c++
function which can idenfity whether a number n
is a prime. First, we create a file called prime.cc
.
bool IsPrime(int n){
if(n<2) return false;
for(int i = 2; i * i <= n; ++i){
if(n%i == 0) return false;
}
return true;
}
We also need to create the prime.h
file.
bool IsPrime(int n);
And modify the gtest.cc
file.
#include <gtest/gtest.h>
#include "prime.h"
TEST(module_name, test_name) {
EXPECT_FALSE(IsPrime(1));
EXPECT_TRUE(IsPrime(2));
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
Run it through terminal using:
$ g++ -std=c++11 gtest.cc prime.cc -lgtest -lpthread
And execute it:
$ ./a.out
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from module_name
[ RUN ] module_name.test_name
[ OK ] module_name.test_name (0 ms)
[----------] 1 test from module_name (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.