A Step-by-step Tutorial on using GTest

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.
最近的文章

MacOS 上自动生成 Anki 单词卡

这是一个通过 Automator 实现的,可以在 MacOS 上轻松安装的 workflow,它可以做到一键将 MacOS 自带的词典内容制作成 Anki 卡片并且保存到 Anki 里,并且可以自定义 Anki 的单词牌组 (Deck) 和卡片模版 (Card Type)。…

Coding继续阅读
更早的文章

长毛象个人向建站

最近搭建了长毛象个人用站点。…

Coding继续阅读