如果你的工程使用到了boost库,并且工程是由CMakeLists.txt构建的,这个文章会展示如何添加boost到Cmake中,其中顺带使用了gtest搭建测试用例
假设有一个工程,目录结构如下
.
├── boost_thread_test.cc
└── CMakeLists.txt
0 directories, 2 files
其中测试用例代码使用到了boost::chrono和boost::thread:
#include <gtest/gtest.h>
#include <boost/thread.hpp>
#include <iostream>
static int make_one_thread() {
boost::thread bt([] {
std::cout << "hello world\n"; });
bt.join();
return 0;
}
static int interrupt_one_thread() {
boost::thread bt([] {
try {
while (1) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(300));
std::cout << "hello world\n";
}
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
} catch (const boost::thread_interrupted& e) {
std::cerr << "thread interruped" << '\n';
}
});
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
bt.interrupt();
bt.join();
boost::chrono::steady_clock::now();
return 0;
}
TEST(test_boost, case_thread1) {
ASSERT_EQ(make_one_thread(), 0); }
TEST(test_boost, case_thread2) {
ASSERT_EQ(interrupt_one_thread(), 0); }
那么 我们的cmakelistst应该这样写,来将gtest和boost线程和时间库添加进去,boost其他非header-only
库同理:
cmake_minimum_required(VERSION 3.6)
set(CMAKE_BUILD_TYPE Debug)
project(unit_test C CXX)
# 此处仅添加thread和chrono 你可以添加你需要的
find_package(Boost REQUIRED COMPONENTS thread chrono)
if(Boost_FOUND)
include_directories(${
Boost_INCLUDE_DIR})
endif()
enable_testing()
find_package(GTest REQUIRED)
set(TEST_LIST
boost_thread_test
)
foreach(src ${
TEST_LIST})
add_executable(${
src} ${
src}.cc)
target_link_libraries(${
src} GTest::GTest GTest::Main Boost::thread Boost::chrono pthread)
#也可以 target_link_libraries(${
src} GTest::GTest GTest::Main boost_thread boost_chrono pthread)
#也可以 target_link_libraries(${
src} GTest::GTest GTest::Main ${
Boost_THREAD_LIBRARY} ${
Boost_CHRONO_LIBRARY} pthread)
#甚至可以 target_link_libraries(${
src} GTest::GTest GTest::Main ${
Boost_LIBRARIES} pthread)
add_test(${
src} ${
src})
endforeach()
测试一下这个测试用例:
mkdir build && cd build && cmake .. && make -j
./boost_thread_test
结果:
Running main() from /build/googletest-OI1WhS/googletest-1.10.0.20201025/googletest/src/gtest_main.cc
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from test_boost
[ RUN ] test_boost.case_thread1
hello world
[ OK ] test_boost.case_thread1 (0 ms)
[ RUN ] test_boost.case_thread2
hello world
hello world
hello world
thread interruped
[ OK ] test_boost.case_thread2 (1001 ms)
[----------] 2 tests from test_boost (1001 ms total)
[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (1003 ms total)
[ PASSED ] 2 tests.
完美~ 顺带还介绍了如何使用gtest和cmake构建单元测试用例 ~~ nice
好了就这样吧 看了一圈国内好像没找到一篇文章好好说如何引用boost库的(大概我眼瞎),正好做一篇
文章评论