google测试框架gtest编译与示例

环境linux
git clone https://github.com/google/googletest
cd googletest
mkdir build
cd build

默认是生成静态库
执行cmake ../
-- The CXX compiler identification is GNU 4.8.5
-- The C compiler identification is GNU 4.8.5
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Found PythonInterp: /usr/bin/python (found version "2.7.12")
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Check if compiler accepts -pthread
-- Check if compiler accepts -pthread - yes
-- Found Threads: TRUE
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zengming/googletest/googletest/build

编译make
Scanning dependencies of target gtest
[ 25%] Building CXX object CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 50%] Linking CXX static library libgtest.a
[ 50%] Built target gtest
Scanning dependencies of target gtest_main
[ 75%] Building CXX object CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
[100%] Linking CXX static library libgtest_main.a
[100%] Built target gtest_main

生成动态库需要加参数
cmake -DBUILD_SHARED_LIBS=ON ../
-- Configuring done
-- Generating done
-- Build files have been written to: /home/zengming/googletest/googletest/build

make
Scanning dependencies of target gtest
[ 25%] Building CXX object CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 50%] Linking CXX shared library libgtest.so
[ 50%] Built target gtest
Scanning dependencies of target gtest_main
[ 75%] Building CXX object CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
[100%] Linking CXX shared library libgtest_main.so
[100%] Built target gtest_main

新建个测试目录test
cd test
拷贝so与头文件
cp ~/googletest/googletest/build/*.so ./
cp ~/googletest/googletest/include/gtest/ ./ -a

生成测试源码main.cpp
#include "gtest/gtest.h"

int test(int a, int b)
{
    return a + b;
}

TEST(test, AddTest) {
    EXPECT_EQ(4, test(2, 2));
}

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

编译
g++ -I ./ -L ./ -lgtest -lgtest_main -lpthread main.cpp

 ./a.out
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from test
[ RUN      ] test.AddTest
[       OK ] test.AddTest (0 ms)
[----------] 1 test from test (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 1 test.
作者:帅得不敢出门  程序员群:31843264

你可能感兴趣的:(C/C++)