gtest单元测试(单元测试(unit test)及覆盖率)及覆盖率
下载下载google test
下载地址:https://github.com/google/googletest/tree/v1.10.x (我用的是1.10.x版本)
main.cc
#include
#include “gtest/gtest.h”
int Add(int a, int b) {
return a + b;
}
int Sub(int a, int b){
return a - b;
}
TEST(testCase, test0){
EXPECT_EQ(14, Add(4, 10));
}
TEST(testCase, test1){
ASSERT_EQ(6, Add(5, 7));
}
TEST(testCase, test2){
EXPECT_EQ(28, Add(8, 10)) << "bugs";
}
int main(int argc, char ** argv) {
std::cout << "Hello, World!" << std::endl;
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); // 执行所有的 test case
}
这个源文件是参考的csdn一个博客的,现在找不到地址了,对原作者表示感谢!!!
CMakeList.txt
cmake_minimum_required(VERSION 3.9)
project(unit_test)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -Wall -fprofile-arcs -ftest-coverage")
set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -Wall -fprofile-arcs -ftest-coverage")
include_directories(./googletest-1.10.x/googletest/include/)
add_subdirectory(./googletest-1.10.x)
set(3RD_LIBS gtest pthread)
add_executable(${PROJECT_NAME} main.cc)
target_link_libraries(${PROJECT_NAME} ${3RD_LIBS})
关键点
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -Wall -fprofile-arcs -ftest-coverage")
set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -Wall -fprofile-arcs -ftest-coverage")
编译、运行编译、运行
mkdir build
cd build
cmake ..
make