CMake file for integrated Visual Studio unit testi

2019-08-04 05:38发布

Visual Studio 2017 has integrated C++ unit testing (native, google test, ctest, etc.). How can I create a CMakeLists.txt file that will create a project like this that will use the integrated IDE testing, for example using either google test or the native microsoft unit testing framework? All of Microsoft's examples unfortunately just create the project in Visual Studio, rather than starting from a CMake file.

Any help is appreciated, thanks!

1条回答
做个烂人
2楼-- · 2019-08-04 06:05

Mikewho,

I setup a small example using Google Test project that works with integrated IDE testing.

Create an empty directory and save these two files:

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);
}

The in a command prompt type

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

Note: I had vcpkg install gtest

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

Make sure you have this installed in Visual Studio 2017
enter image description here

In Tools > Options > Test Adapter for Google Test set the regex to .exe
enter image description here

Build the solution and press Run all in the Test Explorer
enter image description here

The first time it runs it will find the test case

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

I hope this helps?

查看更多
登录 后发表回答