c++ - 使用 Visual Studio 2019 和 cmake 进行谷歌测试

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

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

这是我的 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

所以这很好用。肯定跟open a local folder有关我用来处理我的 cmake 项目的方法。

最佳答案

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

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 中添加。但是,您应该注意,如果您的测试二进制文件有许多测试用例,这会显着降低速度。

关于c++ - 使用 Visual Studio 2019 和 cmake 进行谷歌测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511117/

相关文章:

C++ 和 R : Create a . so 或 .dll

c++ - 什么时候无状态类仿函数可以代替 c 风格的函数?

c++ - 从 std::vector<unsigned char> 转换为不同字节序的 wstring

c# - C# 应用程序的图像监视

asp.net-mvc - 将项目添加到 Visual Studio 上下文菜单

android - 单元测试 : NoSuchMethodError while calling Notification. setLatestEventInfo()

c# - 如果字符串大于 255 个字符,则删除字符

c++ - 结构化绑定(bind)是否适用于 std::vector?

c++ - 在 Visual Studio C++ 的图片框中缩放图片

java - 用于单元测试的 Cassandra 2.1 设置?