如何配置VSCode的launch.json以调试测试视图中的CMake单元测试
用单个launch.json配置调试CMake单元测试
问题背景
项目的CMakeLists.txt中已配置两个单元测试:
######################################## # CMakeLists.txt - Tests # ######################################## add_executable(urltest test/url.cpp) add_test(NAME URLTest COMMAND urltest) add_executable(jsontest test/json.cpp) add_test(NAME JSONTest COMMAND jsontest )
VSCode的Testing视图能正常识别并运行这些测试,但调试时需要为每个测试单独配置launch.json,维护成本高:
{ // launch.json "version": "0.2.0", "configurations": [ { "name": "CTest-urltest", "type": "lldb", "request": "launch", "program": "${workspaceFolder}/build/urltest", "args": [], "initCommands": ["breakpoint set -n main -N entry"], "exitCommands": ["breakpoint delete entry"], "cwd": "${workspaceFolder}" }, { "name": "CTest-jsontest", "type": "lldb", "request": "launch", "program": "${workspaceFolder}/build/jsontest", "args": [], "initCommands": ["breakpoint set -n main -N entry"], "exitCommands": ["breakpoint delete entry"], "cwd": "${workspaceFolder}" } ] }
希望通过单个launch.json配置,自动映射Testing视图中点击的测试程序。
解决方案
使用CMake Tools扩展提供的命令变量${command:cmake.launchTargetPath},它会自动获取当前选中测试的可执行文件路径。最终的launch.json配置如下:
{ "version": "0.2.0", "configurations": [ { "name": "Debug CTest", "type": "lldb", "request": "launch", "program": "${command:cmake.launchTargetPath}", "args": [], "initCommands": ["breakpoint set -n main -N entry"], "exitCommands": ["breakpoint delete entry"], "cwd": "${workspaceFolder}" } ] }
关键说明
${command:cmake.launchTargetPath}:会自动识别当前在Testing视图中选中的测试对应的可执行文件路径,无需手动指定每个测试的程序路径,适配所有CMake单元测试。- 若未使用CMake Tools扩展,可尝试使用
${command:testing.currentTestExecutable},但前者在CMake项目中兼容性更稳定。
内容的提问来源于stack exchange,提问作者MathieuPOUX
相关产品推荐
相关产品推荐

