GoogleTest&Cmake Demo,快速上手

1. 安装相关依赖

  • [ ] - Git
    GoogleTest&Cmake Demo,快速上手

  • [ ] - make
    GoogleTest&Cmake Demo,快速上手

  • [ ] - Cmake
    GoogleTest&Cmake Demo,快速上手

  • [ ] - GCC/G++
    GoogleTest&Cmake Demo,快速上手

2. clone GoogleTest

git clone https://github.com/google/googletest.git
下载完成后:
GoogleTest&Cmake Demo,快速上手

3. 新建项目gtestdemo

在项目目录建如下目录:
GoogleTest&Cmake Demo,快速上手

切换到lib目录,将下载好的GoogleTest源码拷贝到当前目录:

cp -ar ~/workspace/2_test/googletest .

4. 在src目录加源文件

GoogleTest&Cmake Demo,快速上手

// 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目录加源文件

GoogleTest&Cmake Demo,快速上手

//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

GoogleTest&Cmake Demo,快速上手

# 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. 编译

  1. 切换到build目录
    cmake .. -DCMAKE_BUILD_TYPE=Debug
    GoogleTest&Cmake Demo,快速上手

GoogleTest&Cmake Demo,快速上手

  1. make all
    GoogleTest&Cmake Demo,快速上手

  2. 执行
    ** ./test/GoogleTestDemo_test**
    GoogleTest&Cmake Demo,快速上手

转发链接:

https://blog.csdn.net/Fei20140908/article/details/104344462/

GoogleTest&Cmake Demo,快速上手

上一篇:Z-Stack内部API 小结


下一篇:windows无法启动VMware Authorization Service服务