在CLion中设置Google测试

use*_*610 37 c++ googletest linux-mint clion

我已经在网上坐了几个小时,已经尝试在Linux上的Clion上设置Google测试但是却找不到任何东西.

有人可以指导我设置吗?

Dor*_*hal 37

创建新项目

  1. 在我的ClionProjects文件夹中创建一个存储库
    • cd ~/ClionProjects
    • mkdir .repo
    • cd .repo
  2. 从github 克隆DownloadProject
    • git clone https://github.com/Crascit/DownloadProject.git
  3. 使用src和test目录创建一个C++项目

添加以下文件:

的CMakeLists.txt

cmake_minimum_required(VERSION 3.3)

project(MyProjectName)

add_subdirectory(src)
add_subdirectory(test)
Run Code Online (Sandbox Code Playgroud)

SRC /的CMakeLists.txt

#set(core_SRCS ADD ALL SOURCE FILES HERE)

add_library(core ${core_SRCS})
add_executable(exe main.cpp)
target_link_libraries(exe core)
Run Code Online (Sandbox Code Playgroud)

[我们编译一个库,以便我们可以将它包含在Test项目中]

测试/的CMakeLists.txt

cmake_minimum_required(VERSION 3.3)

set(REPO ~/ClionProjects/.repo)

project(Test)

project(Example)

include(CTest)
enable_testing()

#set(gtest_disable_pthreads on) #needed in MinGW
include(${REPO}/DownloadProject/DownloadProject.cmake)
download_project(
        PROJ                googletest
        GIT_REPOSITORY      https://github.com/google/googletest.git
        GIT_TAG             master
        UPDATE_DISCONNECTED 1
        )

add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR} EXCLUDE_FROM_ALL)

#set(test_SRCS ADD ALL TEST SOURCE FILES HERE)
add_executable(runUnitTests gtest.cpp ${test_SRCS})
target_link_libraries(runUnitTests gtest gmock core)
#add_test(runUnitTests runUnitTests) #included in all tutorials but I don't know what it actually does.
Run Code Online (Sandbox Code Playgroud)

测试/ gtest.cpp

#include "gtest/gtest.h"

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您自己使用git项目,最好在项目中包含DownloadProject.cmakeDownloadProjects.CmakeLists.cmake.in文件.

  • @Dormathal.这是一个可怕的答案,导致那些不理解CMake搞砸他们整个配置的人.您正在让他们重写他们的CMakeLists.txt文件而不了解更改的影响.一个好的答案解释了每个变化的作用.例如,您可以解释为什么要创建其他CMakeList文件.这是怎么得到这么多的赞成超出我的! (5认同)
  • 我不得不从`test/CMakeLists.txt`中取出`core`并重新编写`src/CMakeLists.txt`.在那之后,它工作了! (2认同)

小智 6

1.Git克隆谷歌测试 C ++测试框架

From https://github.com/google/googletest.git
Run Code Online (Sandbox Code Playgroud)

2.包括google-test目录

#Add the google test subdirectory
add_subdirectory(PATH_TO_GOOGLETEST)

#include googletest/include dir
include_directories(PATH_TO_GOOGLETEST/googletest/include)

#include the googlemock/include dir
include_directories(PATH_TO_GOOGLETEST/googlemock/include)
Run Code Online (Sandbox Code Playgroud)

3.将可执行文件与google-test链接(这是在创建可执行文件之后)

#Define your executable
add_executable(EXECUTABLE_NAME ${SOURCE_FILES})

#Link with GoogleTest
target_link_libraries(EXECUTABLE_NAME gtest gtest_main)

#Link with GoogleMock
target_link_libraries(EXECUTABLE_NAME gmock gmock_main)
Run Code Online (Sandbox Code Playgroud)