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/