gpt4 book ai didi

c++ - 如何在VS Code中运行测试和调试Google Test项目?

转载 作者:行者123 更新时间:2023-12-03 07:06:57 25 4
gpt4 key购买 nike

我想运行样本测试并调试Google Test project。我在Ubuntu 16.04 LTS上使用VS Code。

  • 我在/home/user/Desktop/projects/cpp/googletest
  • 本地克隆了项目
  • mybuild处创建了一个名为/home/user/Desktop/projects/cpp/mybuild的新目录。
  • 根据此处的README说明:https://github.com/google/googletest/tree/master/googletest我使用了cmake -Dgtest_build_samples=ON /home/user/Desktop/projects/cpp/googletest命令来构建项目,这生成了一堆文件,显然构建成功。

  • 现在,我有两个问题:
  • 如何运行项目的样本测试?
  • 如何调试这些测试和项目的源代码?
  • 最佳答案

  • 从一个干净的目录开始:
  • /home/user/Desktop/projects/cpp/ # your project lives here
  • 添加cmake文件(CMakeLists.txt),源文件和测试文件。现在,目录如下所示:
  • └─cpp/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp
  • 克隆并将googletest添加到以下目录:
  • └─cpp/
    ├─ googletest/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp
  • 打开您的CMakeLists.txt,然后输入以下内容:
  • cmake_minimum_required(VERSION 3.12) # version can be different

    project(my_cpp_project) #name of your project

    add_subdirectory(googletest) # add googletest subdirectory

    include_directories(googletest/include) # this is so we can #include <gtest/gtest.h>

    add_executable(mytests mytests.cpp) # add this executable

    target_link_libraries(mytests PRIVATE gtest) # link google test to this executable
  • 示例的myfunctions.h内容:
  • #ifndef _ADD_H
    #define _ADD_H

    int add(int a, int b)
    {
    return a + b;
    }

    #endif
  • 示例的mytests.cpp内容:
  • #include <gtest/gtest.h>
    #include "myfunctions.h"

    TEST(myfunctions, add)
    {
    GTEST_ASSERT_EQ(add(10, 22), 32);
    }

    int main(int argc, char* argv[])
    {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
    }
    现在,您只需要运行测试。有多种方法可以做到这一点。
    在终端中,在 build/中创建一个 cpp/目录:
    mkdir build
    您的目录现在应如下所示:
    └─cpp/
    ├─ build/
    ├─ googletest/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp
    接下来进入 build目录:
    cd build
    然后运行:
    cmake ..
    make
    ./mytests
    替代方式:
  • 为VS Code
  • 安装 CMake Tools 扩展
  • 在底部栏中,您可以看到要构建/运行的当前目标(在方括号中 Build [mytest] Run [mytest] ):
  • 然后只需单击运行按钮。

  • enter image description here

    自行构建Google测试
    使用终端:
  • 进入目录/home/user/Desktop/projects/cpp/googletest
  • 在其中创建build/,使其看起来如下所示:
  • └─cpp/googletest/
    ├─ build/
    ├─ ...other googletest files
  • cd build
  • 运行:cmake -Dgtest_build_samples=ON -DCMAKE_BUILD_TYPE=Debug ..
  • make -j4
  • ./googletest/sample1_unittest

  • 使用VS代码
  • googletest文件夹打开到VS Code
  • CMake扩展将提示您进行配置,允许它
  • 您将看到.vscode目录。在其中是settings.json文件,将其打开,然后添加以下内容:
  •     "cmake.configureSettings": { "gtest_build_samples": "ON" }
  • 使用底部栏中的按钮
  • 进行构建和运行

    关于c++ - 如何在VS Code中运行测试和调试Google Test项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62910867/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com