使用Visual Studio 2019和cmake进行google测试

时间:2019-06-09 00:31:05

标签: c++ visual-studio unit-testing cmake googletest

我正在尝试使用Visual Studio 2019和cmake设置Google测试。

这是我的CMakeFileLists.txt内容:

cmake_minimum_required(VERSION 3.0)
project(test_me)

# GTest
enable_testing()
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})

# Unit Tests
# Add test cpp file
add_executable( runUnitTests tests.cpp)
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests ${GTEST_BOTH_LIBRARIES})
add_test( runUnitTests runUnitTests )

我的tests.cpp文件看起来像这样:

#include <gtest/gtest.h>

TEST(ABC, TEST1) {
    EXPECT_EQ(true, true);
}

TEST(ABC, TEST2) {
    ASSERT_TRUE(2 == 2);
}

这个最小的例子来自另一个stackoverflow问题: CMake file for integrated Visual Studio unit testing

那是我构建应用程序后得到的: enter image description here

一个名为runUnitTests的测试。但是,在上述问题的答案图中,我希望看到每个测试函数的名称。像这样:

runUnitTests
- ABC
  - TEST1
  - TEST2

我已经使用新的Visual Studio解决方案对其进行了测试,并添加了Google单元测试项目。将测试功能粘贴到该项目中,结果如下图所示:

enter image description here

所以这很好。它必须与我用来处理cmake项目的open a local folder方法有关。

1 个答案:

答案 0 :(得分:0)

以下是您问题的可能答案:

cmake_minimum_required(VERSION 3.10)

project(test_me)

enable_testing()

find_package(GTest REQUIRED)
include(GoogleTest)

add_executable(runUnitTests tests.cpp)
target_link_libraries(runUnitTests GTest::GTest GTest::Main)

gtest_discover_tests(runUnitTests)

在您的测试二进制文件中发现完整测试列表的命令是 gtest_discover_tests(),它是 GoogleTest CMake 模块的一部分(您可以使用 cmake --help-module GoogleTest 在本地查看文档) .此模块已随 CMake 3.9 引入,但命令 gtest_discover_tests() 仅在 CMake 3.10 中添加。但是,您应该注意,如果您的测试二进制文件有很多测试用例,这会显着降低速度。