首页 > 解决方案 > 用于集成 Visual Studio 单元测试的 CMake 文件

问题描述

Visual Studio 2017 集成了 C++ 单元测试(native、google test、ctest 等)。如何创建一个 CMakeLists.txt 文件,该文件将创建一个这样的项目,该项目将使用集成 IDE 测试,例如使用谷歌测试或本机微软单元测试框架?不幸的是,微软的所有示例都只是在 Visual Studio 中创建项目,而不是从 CMake 文件开始。

任何帮助表示赞赏,谢谢!

标签: c++visual-studiounit-testingcmake

解决方案


迈克谁,

我使用 Google Test 项目设置了一个小示例,该项目适用于集成 IDE 测试。

创建一个空目录并保存这两个文件:

CMakeLists.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 )

测试.cpp

#include <gtest/gtest.h>

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

在命令提示符类型中

mkdir build
cd build
cmake .. "-DCMAKE_TOOLCHAIN_FILE=C:/dev/vcpkg/scripts/buildsystems/vcpkg.cmake"

注意:我有 vcpkg install gtest

C:\dev\vcpkg>vcpkg.exe install gtest

确保你在 Visual Studio 2017 中安装了这个
在此处输入图像描述

在 Tools > Options > Test Adapter for Google Test 中,将正则表达式设置为 .exe
在此处输入图像描述

构建解决方案并在测试资源管理器中按全部运行
在此处输入图像描述

第一次运行它会找到测试用例

[12/3/2018 8:38:41 AM Informational] ------ Run test started ------
[12/3/2018 8:38:42 AM Warning] Could not locate debug symbols for 'C:\dev\cpptests\GoogleTest\build\Debug\runUnitTests.exe'. To make use of '--list_content' discovery, ensure that debug symbols are available or make use of '<ForceListContent>' via a .runsettings file.
[12/3/2018 8:38:42 AM Informational] Test Adapter for Google Test: Test execution starting...
**[12/3/2018 8:38:42 AM Informational] Found 1 tests in executable** C:\dev\cpptests\GoogleTest\build\Debug\runUnitTests.exe
[12/3/2018 8:38:42 AM Informational] Running 1 tests...
[12/3/2018 8:38:42 AM Informational] Google Test execution completed, overall duration: 00:00:00.2390446
[12/3/2018 8:38:42 AM Informational] ========== Run test finished: 1 run (0:00:01.2668844) ==========

我希望这有帮助?


推荐阅读