用于集成Visual Studio单元测试的CMake文件

时间:2018-12-02 18:26:42

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

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

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

迈克,

我使用与集成IDE测试一起使用的Google Test项目设置了一个小示例。

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

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 )

tests.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安装gtest

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

确保已在Visual Studio 2017中安装了此程序
enter image description here

在工具>选项> Google Test的测试适配器中,将正则表达式设置为.exe
enter image description here

构建解决方案,然后在Test Explorer中按Run all
enter image description here

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

[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) ==========

我希望这对您有帮助吗?