在CMake裡面使用Google Test

之前想在CMake專案裡面使用,似乎很少有人提到如何把Google Test跟CMake很好的整合起來,所以寫了一篇簡單的心得來做個紀錄。

首先取得Google Test

我個人的習慣是把目錄分成這幾個目錄,我拿我現在正在寫的一個小專案來做例子:

1
2
3
4
5
6
7
8
9
10
.
├── CMakeLists.txt
├── README.md
├── deps
│   └── googletest
├── main.cpp
├── src
│   └── IHost.h
└── test
└── twitter_basic.cpp

其中deps專門用來放3rd party dependency。我個人是不太建議使用系統安裝來裝這種那麼小的東西,而且這會造成別人使用這個project的麻煩。

我自己是習慣使用git submodule來裝這種git專案就能拿到的東西,所以取得方法會像是這樣 :

1
2
3
4
5
6
7
8
➜ Octo git:(master) ✗ cd dep
➜ dep git:(master) ✗ git submodule add git@github.com:google/googletest.git
Cloning into '/Users/rayer/Develop/Octo/dep/googletest'...
remote: Counting objects: 7670, done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 7670 (delta 3), reused 7 (delta 2), pack-reused 7654
Receiving objects: 100% (7670/7670), 2.61 MiB | 356.00 KiB/s, done.
Resolving deltas: 100% (5686/5686), done.

這樣deps底下就會有googletest這個子目錄了。其他人clone你的專案的時候,記得在README.md提醒一下對方要先git submodule init來取得所有的submodule。

當然取得google test的source code方法不只一種,你可以直接在deps裡面下git clone,或者直接download source code硬解到底下,結果應該差不多。

CMake裡面的設定

Google Test完整支援CMake,所以整個構造會很簡單。其中下面的test/twitter_basic.cpp就是你寫你TEST TEST_F TEST_P的位置,請自己建立一個檔案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 可加可不加,在這個範例不影響
enable_testing()
# 把google test整個cmake managed dir全部加進來
add_subdirectory(deps/googletest)
# 宣告include目錄有google test,通常順便連googlemock一起加入
include_directories(deps/googletest/googletest/include)
include_directories(deps/googletest/googlemock/include)
# 測試的主體。main宣告google test已經幫你宣告好了,直接用就是,就是gtest_main.cc
add_executable(twitter_test deps/googletest/googletest/src/gtest_main.cc test/twitter_basic.cpp)
# Link gtest library
target_link_libraries(twitter_test gtest)

這樣基本上就能跑了,看起來會像這樣:

1
2
3
4
5
6
7
8
9
10
11
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SANITY
[ RUN ] SANITY.sanity
[ OK ] SANITY.sanity (0 ms)
[----------] 1 test from SANITY (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 1 test.