Open2

Visual Studio/CMake/Google Test

日照ちゃん日照ちゃん

Visual StudioのTest Explorerからテストを実行したり、テスト用のtargetをデバッグ実行したいときにやっておいたほうがいいこと。

環境

  • cmake version 3.31.6-msvc6
  • Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.14.6 (June 2025)

CMakeを使用してVisual Studio用のソリューションファイルを生成せずに、直接CMakeプロジェクトを使用している。

CMakeでGoogle TestのWORKING_DIRECTORYを設定する

Google TestはCMake上でtargetのWORKING_DIRECTORYを設定できる。

gtest_discover_tests(
    target
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)

例えば、下記の構成のプロジェクトで libA が自身のディレクトリ配下のテスト用リソースを読み込みたいとき、WORKING_DIRECTORY${CMAKE_SOURCE_DIR}にすることで、projectからの相対ディレクトリを使用することができる。

project/
├── libs/
│   ├── libA/
│   │   ├── CMakeLists.txt
│   │   ├── res/
│   │       └── sample.txt
...
// OK
EXPECT_TRUE(std::filesystem::exists("libs/libA/res/sample.txt"));

ただし、ここで指定したWORKING_DIRECTORYの設定はVisual StudioのText Explorerからだと無視される。

Visual StudioのTest Adapter for Google Testの設定

Visual Studioのメニューバーから

  1. [Tools]
  2. [Options]
  3. [Test Adapter for Google Test]を開き、Working Directory の設定を確認する。

デフォルトだと $(ExecutableDir) になっているのでこれを $(SolutionDir) に設定することで、Test Explorerからテストを実行したときのworking directoryを変更することができる。

ただしプロジェクトごとに変更できるものではないので注意。(これを何とかする方法はあるのかな?)

Visual Studioのlaunch.vs.jsonの設定

Solution ExplorerからCMakeのtargetを右クリック(またはStartup Item)でのデバッグ実行のworking directoryは、Test Adapter for Google Testとは別の設定を行う必要がある。
これはlaunch.vs.jsonを作成することで解決できる。
https://learn.microsoft.com/en-us/visualstudio/ide/customize-build-and-debug-tasks-in-visual-studio?view=vs-2022

必要最低限の簡易なlaunch.vs.jsonを作成する。

{
    "version": "0.2.1",
    "defaults": {},
    "configurations": [
        {
            "type": "default",
            "project": "CMakeLists.txt",
            "projectTarget": "target.exe (libs\\libA\\target.exe)",
            "name": "target",
            "currentDir": "${workspaceRoot}"
        }
    ]
}

currentDir${workspaceRoot}を指定することでプロジェクトからの相対ディレクトリをworking directoryとして使用することができる。

projectTargetはVisual StudioのStartup itemとして表示される名前と完全に一致している名前を設定しなければいけない点に注意。
https://learn.microsoft.com/en-us/cpp/build/launch-vs-schema-reference-cpp?view=msvc-170

The target must match the name in the Startup Item dropdown.

補足

(2025/6/21 現在)
https://developercommunity.visualstudio.com/t/Cant-create-launchvsjson-for-CMake-ex/10913931
Visual Studio上からlaunch.vs.jsonが正常に作成できない不具合が発生しているので手動で作成する必要がある。

終わり

ここまでの設定でVisual Studio上からテストを実行することは問題なくできるようになったはず。

日照ちゃん日照ちゃん

WORKING_DIRECTORYの設定はVisual StudioのText Explorerからだと無視される

詳細はもちろん自分には全くわからないのだけど、2018年のdeveloper community上では以下のようなやりとりが残っていた。

Test Explorer doesn’t call CTest because it needs to be able to debug the process (and visual studio doesn’t support child process debugging).
https://developercommunity.visualstudio.com/t/cmake-test-explorer-doesnt-escape-arguments-like-c/228522

Google TestやCatch2はCTestを使用してWORKING_DIRECTORYの設定を行っており、Visual StudioはCTestを使用せず独自のTest Runnerを使用しているから無視…ということなのかもしれない。(とはいえもう少し良い感じになってほしい。)