我在 kata 项目下工作,学习如何用 C++ 编写单元测试 ( link to the repository )。该项目中的元素之一是 DictionaryPath 库。它被放置在一个带有专用 CMakeFile.txt
的单独目录中:
cmake_minimum_required(VERSION 3.6 FATAL_ERROR)
add_library(DictionaryPath
include/DictionaryPath/Dictionary.h
src/Dictionary.cpp
include/DictionaryPath/DictionaryPath.h
src/DictionaryPath.cpp
src/WordsGraph.cpp
src/WordsGraph.h
src/DijkstraAlgorithmImpl.cpp
src/DijkstraAlgorithmImpl.h
src/Path.cpp
src/Path.h
src/Graph.h
src/ShortestPathAlgorithm.h
src/DijkstraAlgorithm.h)
target_include_directories(DictionaryPath PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE src)
它可以与其他目标(库的客户端)一起查找,但是当我尝试在同一子目录中添加单元测试时,我遇到了如何定义单元测试目标的问题。方程WordsGraph
类。我定义了一个目标:
add_executable(WordsGraphTest test/WordsGraphTest.cpp)
target_link_libraries(WordsGraphTest GTest::main DictionaryPath)
add_test(NAME WordsGraphTest COMMAND WordsGraphTest)
但是如果我尝试引用 WordsGraph
头文件,我有:
test/WordsGraphTest.cpp:9:10: fatal error: 'WordsGraph.h' file not found
我明白一个原因 - src/
中的文件是私有(private)的,但是在这种情况下如何测试库内部文件而不实现链接到它的每个目标?我应该在每个单元测试中重复编译必要的库文件吗?
最佳答案
add_library(DictionaryPath
...
src/WordsGraph.h
...
)
target_include_directories(DictionaryPath PUBLIC
...
PRIVATE src)
WordsGraph.h
位于 src
中,并且您将 src
声明为 DictionaryPath
的私有(private)包含目录。
如果您在创建单元测试时只想调用 target_link_libraries
,则应该将 WordsGraph.h
移至 include
,或将 src
声明为公共(public)或接口(interface)包含目录。
如果您不想将 WordsGraph.h
移动到 include
中,也不想将 src
声明为公共(public)或接口(interface)包含目录,您可以应该添加对 target_include_directories
的调用:
add_executable(WordsGraphTest test/WordsGraphTest.cpp)
target_link_libraries(WordsGraphTest GTest::main DictionaryPath)
target_include_directories(WordsGraphTest PRIVATE src)
add_test(NAME WordsGraphTest COMMAND WordsGraphTest)
关于c++ - CMake:如何设置库的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863228/