CMake单元结构有许多测试

时间:2018-01-05 09:40:15

标签: c++ unit-testing cmake

我想设置cmake来运行带有单元测试的项目。项目结构如下:

|---CMakeLists.txt
|---build
|---source
|   |---CMakeLists.txt
|   |---many .cpp and .h files
|---tests
|   |---CMakeLists.txt
|   |---many .cpp files

tests中的源文件使用Boost unit_test.h库。

我的外CMakeLists.txt如下:

cmake_minimum_required(VERSION 2.8.11)

set(CMAKE_CXX_FLAGS "-std=c++11")

project(MyProject CXX)
add_subdirectory(source)
add_subdirectory(tests)
enable_testing()

CMakeLists.txt文件夹中的source是:

file( GLOB LIB_SOURCES *.cpp )
file( GLOB LIB_HEADERS *.h )
add_library( MyProject_lib ${LIB_SOURCES} ${LIB_HEADERS} )

CMakeLists.txt文件夹中的tests为:

# require old policy to allow for source files containing the name "test"
cmake_policy(SET CMP0037 OLD)
# Locate Boost libraries: unit_test_framework, date_time and regex
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.59 REQUIRED COMPONENTS unit_test_framework date_time regex)

include_directories("${CMAKE_SOURCE_DIR}/source" ${Boost_INCLUDE_DIRS})

file(GLOB APP_SOURCES *.cpp)
foreach(testsourcefile ${APP_SOURCES})
    string(REPLACE ".cpp" "" testname ${testsourcefile})
    add_executable(${testname} ${testsourcefile})
    target_link_libraries(${testname} LINK_PUBLIC ${Boost_LIBRARIES} MyProject_lib)
    add_custom_target(targetname)
    add_custom_command(TARGET targetname POST_BUILD COMMAND ${testname})
endforeach(testsourcefile ${APP_SOURCES})

如果我使用add_custom_targetadd_custom_command注释这些行,则此配置的结果是库已正确构建和链接,但没有编译任何测试。

如果我不对add_custom_targetadd_custom_command的两行进行评论,则运行cmake时出现的错误是:

CMake Error at tests/CMakeLists.txt:25 (add_custom_target):
add_custom_target cannot create target "targetname" because another target
with the same name already exists.  The existing target is a custom target
created in source directory "/tests".  See
documentation for policy CMP0002 for more details.

由于我有大量的测试,逐一列出它们是不切实际的。我想让cmake找到所有的.cpp文件,就像在源文件夹中的库一样,编译并运行它们。

1 个答案:

答案 0 :(得分:0)

这是我在我的库中使用的解决方案:

FILE( GLOB log_testprograms *.cpp )

FOREACH( testsource ${log_testprograms} )
   GET_FILENAME_COMPONENT( filename ${testsource} NAME_WE )
   celma_add_celma_boost_testprogram( ${filename} )
ENDFOREACH()

celma_add_celma_boost_testprogram是这样的宏:

macro( celma_add_celma_boost_testprogram  filename )
   add_executable(        ${filename}  ${filename}.cpp )
   target_link_libraries( ${filename}  celma ${Boost_Test_Link_Libs} )
   add_test(              ${filename}  ${CMAKE_CURRENT_BINARY_DIR}/${filename} )
endmacro( celma_add_celma_boost_testprogram )

Celma是我的库的名称,变量Boost_Test_Link_Libs包含要链接的Boost库列表,包括Boost.Test库。