Loading

gtest入门

一、gtest简介

gtest是一个跨平台(Liunx、Mac OS X、Windows、Cygwin、Windows CE and Symbian)C++测试框架,有google公司发布。gtest测试框架是在不同平台上为编写C++测试而生成的。

gtest下载网站

https://github.com/google/googletest

二、gtest的编译

下载好gtest-1.7.0.zip之后解压

cd googletest
mkdir build
cmake -G Ninja  .. 
ninja

build/lib目录下生成libgtest.a和libgtest_main.a库

三、gtest使用

3.1、新建项目

(base) ➜  maingtest tree 
.
├── CMakeLists.txt
└── main.cpp

3.2、将gtest资源放到项目中

将项目中的build/lib文件夹和googletest/include文件夹

(base) ➜  maingtest tree 
.
├── CMakeLists.txt
├── include
│   └── gtest
│       ├── ...
│       ├── gtest.h
│       └── internal
│           ├── custom
│           │   ├── ...
│           │   └── gtest.h
│           ├── ...
│           └── gtest-type-util.h
├── lib
│   ├── libgtest.a
│   └── libgtest_main.a
└── main.cpp

首先修改CMakeLists.txt

cmake_minimum_required(VERSION 3.22)
project(maingtest)
set(CMAKE_CXX_STANDARD 14)
include_directories(include)
link_directories(lib)
add_executable(maingtest main.cpp)
target_link_libraries(
        maingtest
        libgtest.a
)

修改main.cpp

#include "gtest/gtest.h"
int add(int a,int b){
    return a+b;
}

TEST(fun, add){
EXPECT_EQ(1, add(2,-1));
}

int main(int argc, char** argv){
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

在maingtest目录下

(base) ➜  maingtest mkdir build
(base) ➜  maingtest cd build
(base) ➜  build cmake -G Ninja  .. 
-- The C compiler identification is AppleClang 13.0.0.13000027
...
-- Build files have been written to: /Users/.../.../maingtest/build
(base) ➜  build ninja
[2/2] Linking CXX executable maingtest
(base) ➜  build ls
CMakeCache.txt      CMakeFiles          build.ninja         cmake_install.cmake maingtest
(base) ➜  build ./maingtest 
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from fun
[ RUN      ] fun.add
[       OK ] fun.add (0 ms)
[----------] 1 test from fun (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

可以看到成功的进行了测试并且通过了一个test单元测试。

posted @ 2022-09-30 20:42  xine  阅读(1236)  评论(0编辑  收藏  举报