簡體   English   中英

如何在 VS Code 中運行測試和調試 Google Test 項目?

[英]How to run tests and debug Google Test project in VS Code?

我想運行示例測試並調試Google 測試項目 我在 Ubuntu 16.04 LTS 上使用 VS Code。

  • 我在/home/user/Desktop/projects/cpp/googletest本地克隆了項目,
  • /home/user/Desktop/projects/cpp/mybuild創建了一個名為mybuild的新目錄。
  • 根據此處的 README 說明: https://github.com/google/googletest/tree/master/googletest我使用了命令cmake -Dgtest_build_samples=ON /home/user/Desktop/projects/cpp/googletest來構建項目這生成了一堆文件,顯然構建成功了。

現在,我有兩個問題:

  1. 如何運行項目的示例測試?

  2. 如何調試這些測試和項目的源代碼?

  1. 從一個干凈的目錄開始:
/home/user/Desktop/projects/cpp/ # your project lives here
  1. 添加您的 cmake 文件 (CMakeLists.txt)、源文件和測試文件。 該目錄現在如下所示:
└─cpp/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp
  1. 克隆並將googletest添加到此目錄:
└─cpp/
    ├─ googletest/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp
  1. 打開您的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
  1. 示例中myfunctions.h的內容:
#ifndef _ADD_H
#define _ADD_H

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

#endif
  1. 示例中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();
}

現在你只需要運行測試。 有多種方法可以做到這一點。

在終端中,在cpp/中創建一個build/目錄:

mkdir build

您的目錄現在應該如下所示:

└─cpp/
    ├─ build/
    ├─ googletest/
    ├─ CMakeLists.txt
    ├─ myfunctions.h
    └─ mytests.cpp

接下來 go 進入build目錄:

cd build

然后運行:

cmake ..
make
./mytests

替代方式:

  • 為 VS Code 安裝CMake Tools擴展
  • 在底部欄中,您可以看到要構建/運行的當前目標(在方括號中Build [mytest]Run [mytest] ):
  • 然后只需單擊運行按鈕。

在此處輸入圖像描述


構建 Google 測試本身

使用終端:

  1. Go 進入目錄/home/user/Desktop/projects/cpp/googletest
  2. 在其中創建build/使其如下所示:
└─cpp/googletest/
    ├─ build/
    ├─ ...other googletest files
  1. cd build
  2. 運行: cmake -Dgtest_build_samples=ON -DCMAKE_BUILD_TYPE=Debug..
  3. make -j4
  4. ./googletest/sample1_unittest

使用 VS 代碼

  1. 在 VS Code 中打開googletest文件夾
  2. CMake 擴展會提示配置,允許
  3. 您將看到一個.vscode目錄。 里面是settings.json文件,打開它,添加以下內容:
    "cmake.configureSettings": { "gtest_build_samples": "ON" }
  1. 從底部欄中的按鈕構建和運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM