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.
更早的文章

长毛象个人向建站

前几天搭建了个人站。采用的 VPS 是 Vultr 5 USD 的配置。优点长毛象的优点不再赘述,这里只写主观的个人站的优点。 成本低。服务器用的是 vultr 上最便宜的,域名也直接采用了子域名的方式。 不需要配置邮件服务。搭建时可以直接用命令行注册一个 admin 帐号,系统会自动生成一串很长的密码。将密码记录下来在网页端修改一下就行。(看到有站长忘记了密码,也可以通过数据库修改) (至少目前)不需要将媒体文件存储在其他储存服务上。 本站时间轴上全是自己的消息,跨站时间轴上全是...…

Coding继续阅读