【问题标题】:CMake: How to setup unit testing of a libraryCMake:如何设置库的单元测试
【发布时间】:2016-10-04 23:26:49
【问题描述】:

我在一个 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/ 中的文件是私有的,但在这种情况下如何测试库内部文件而不为链接到它的每个目标实现?我应该在每个单元测试中重复编译必要的库文件吗?

【问题讨论】:

    标签: c++ unit-testing cmake tdd googletest


    【解决方案1】:
    add_library(DictionaryPath
            ...
            src/WordsGraph.h
            ...
    )
    
    target_include_directories(DictionaryPath PUBLIC
        ...
        PRIVATE src)
    

    WordsGraph.hsrc 中,并且您将src 声明为DictionaryPath 的私有包含目录。

    如果您不想在创建单元测试时调用target_link_libraries,您应该将WordsGraph.h 移动到include,或者将src 声明为公共或接口包含目录。

    如果您不想将WordsGraph.h 移动到include,也不想将src 声明为公共或接口包含目录,则应添加对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)
    

    【讨论】:

      【解决方案2】:

      你遇到的问题应该很容易解决(WordsGraph.h not found)。您可以使用 include_directories 或 target_include_directories。

      【讨论】:

        猜你喜欢
        • 2020-12-23
        • 1970-01-01
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2015-01-25
        • 2014-03-02
        • 1970-01-01
        相关资源
        最近更新 更多