GoogleTest&Cmake Demo,快速上手
阿新 • • 發佈:2021-09-04
1. 安裝相關依賴
-
[ ] - Git
-
[ ] - make
-
[ ] - Cmake
-
[ ] - GCC/G++
2. clone GoogleTest
git clone https://github.com/google/googletest.git
下載完成後:
3. 新建專案gtestdemo
在專案目錄建如下目錄:
切換到lib目錄,將下載好的GoogleTest原始碼拷貝到當前目錄:
cp -ar ~/workspace/2_test/googletest .
4. 在src目錄加原始檔
// Formula.cpp #include "Formula.h" int Formula::bla(int a) { return a * 2; }
// Formula.h
#ifndef _FORMULA_H_
#define _FORMULA_H_
class Formula{
public:
static int bla(int a);
};
#endif
//main.cpp
#include <iostream>
#include "Formula.h"
int main()
{
std::cout << "Bla: " << Formula::bla(2) << std::endl;
return 0;
}
當然CMakeList.txt也不能少:
#設定 BINARY 為專案名IndexProject set(BINARY ${CMAKE_PROJECT_NAME}) # 1 # add_executable(ExampleProject main.cpp file1.cpp file1.h) # 2 file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp) set(SOURCES ${SOURCES}) add_executable(${BINARY}_run ${SOURCES}) # 為了讓單元測試的時候src下的程式碼能被作為靜態連結庫使用 add_library(${BINARY}_lib STATIC ${SOURCES})
5. 在test目錄加原始檔
//main.cpp
#include "gtest/gtest.h"
int main(int argc,char **argv)
{
::testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
//FormulaTest.cpp #include "gtest/gtest.h" #include "Formula.h" TEST(blaTest ,testdemo1) { //arrang //act //assert EXPECT_EQ(Formula::bla(0),0); //pass EXPECT_EQ(Formula::bla(2),4); //pass EXPECT_EQ(Formula::bla(6),6); //Not pass }
以及CMakeList.txt:
#設定 BINARY 為專案名IndexProject
set(BINARY ${CMAKE_PROJECT_NAME})
# 1
# add_executable(ExampleProject main.cpp file1.cpp file1.h)
# 2
file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)
set(SOURCES ${SOURCES})
add_executable(${BINARY}_run ${SOURCES})
# 為了讓單元測試的時候src下的程式碼能被作為靜態連結庫使用
add_library(${BINARY}_lib STATIC ${SOURCES})
5. 在根目錄加CMakeList.txt
# cmake version
cmake_minimum_required(VERSION 3.10)
# project name
project(GoogleTestDemo)
#採用c++14標準
set(CMAKE_CXX_STANDARD 14)
include_directories(src)
add_subdirectory(src)
add_subdirectory(test)
add_subdirectory(lib/googletest)
以上就完成了,接下來是編譯操作
6. 編譯
- 切換到build目錄
cmake .. -DCMAKE_BUILD_TYPE=Debug
-
make all
-
執行
**./test/GoogleTestDemo_test
**
轉發連結:
https://blog.csdn.net/Fei20140908/article/details/104344462/