首先需要在本机上编译和安装Google GTest的最新版本。
macos - How to install GTest on Mac OS X with homebrew? - Stack Overflow
参考回答15的Update Revision就可以。
这样会把Google Test和GMock一起装上。
然后就是写两个CMakeLists.txt文件试一下。
本工程测试最简单的加减法,因为一次build只能定义一个main函数,所以多个子模块的测试和主模块main函数是放在不同的CMakeLists.txt文件里面的。编译出来的二进制文件也不一样。
本工程的结构如下,
Screen Shot 2021-08-06 at 3.28.37 PM.png
程序代码如下,
main.cpp
#include <iostream>
#include "cal/cal.h"
int main(int argc, char* argv[]) {
int c = add(2, 3);
std::cout << "add(2, 3) = " << c << std::endl;
return 0;
}
main.cpp的CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(gtest_test)
add_definitions(-std=c++14)
add_definitions(-g)
find_package(Boost REQUIRED COMPONENTS
system
filesystem
serialization
program_options
thread
)
include_directories(${Boost_INCLUDE_DIRS} /usr/local/include ${CMAKE_CURRENT_SOURCE_DIR}/include)
LINK_DIRECTORIES(/usr/local/lib)
file( GLOB APP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.h
${CMAKE_CURRENT_SOURCE_DIR}/include/cal/impl/*.cpp)
foreach( sourcefile ${APP_SOURCES} )
file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${sourcefile})
if( "${filename}" STREQUAL "main.cpp")
string(REPLACE ".cpp" "" file ${filename})
add_executable(${file} ${APP_SOURCES})
target_link_libraries(${file} ${Boost_LIBRARIES})
target_link_libraries(${file} pthread ssl crypto libgtest.a libgmock.a)
endif()
endforeach( sourcefile ${APP_SOURCES})
cal.h
#ifndef _FREDRIC_CAL_H_
#define _FREDRIC_CAL_H_
int add(int a, int b);
int sub(int a, int b);
#endif
cal.cpp
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
cal_test.cpp
#include <gtest/gtest.h>
#include "cal/cal.h"
GTEST_TEST(CalSuite, AddTest) {
ASSERT_EQ(5, add(3,2));
}
GTEST_TEST(CalSuite, SubTest) {
ASSERT_EQ(1, sub(3, 2));
}
cal_test.cpp的CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(cal_test)
add_definitions(-std=c++14)
add_definitions(-g)
find_package(Boost REQUIRED COMPONENTS
system
filesystem
serialization
program_options
thread
)
include_directories(${Boost_INCLUDE_DIRS} /usr/local/include ${CMAKE_CURRENT_SOURCE_DIR}/../../)
LINK_DIRECTORIES(/usr/local/lib)
file( GLOB APP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.h
${CMAKE_CURRENT_SOURCE_DIR}/../impl/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
foreach( sourcefile ${APP_SOURCES} )
file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${sourcefile})
string(FIND "${filename}" "test.cpp" "TEMP")
if( NOT "${TEMP}" STREQUAL "-1" )
string(REPLACE ".cpp" "" file ${filename})
add_executable(${file} ${APP_SOURCES})
target_link_libraries(${file} ${Boost_LIBRARIES})
target_link_libraries(${file} ssl crypto libgtest.a libgtest_main.a libgmock.a pthread)
endif()
endforeach( sourcefile ${APP_SOURCES})
gtest执行的效果如下,还是比较直观的。比自己在main函数里面写完测试再注释强点
image.png
网友评论