# Gtest в VSCode

В Visual Studio Code есть набор расширений для работы с Google Test:

* [Google Test Explorer for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=OpenNingia.vscode-google-test-adapter)
* [GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)

Далее представлен пример использования расширений.

***

## Общая структура программы

```txt
project
├── build [CMake generated dir]
├── include [dir]
    ├── quat.hpp [header file]
├── src [dir]
    ├── main.cpp [source file]
├── test [dir]
    ├── tests.cpp [source file with unit tests]
├── CMakeLists.txt [file]
```

{% code title="CMakeLists.txt" overflow="wrap" lineNumbers="true" %}

```cmake
cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 23)

project(gtest_program)

include_directories(include)
add_executable(program src/main.cpp)

enable_testing()
find_package(GTest CONFIG REQUIRED)

add_executable(gtest_program test/tests.cpp)
target_link_libraries(gtest_program PRIVATE GTest::gtest GTest::gtest_main)

add_test(NAME all_tests COMMAND gtest_program)
```

{% endcode %}

`find_package` находит и загружает настройки из внешнего проекта. В этом случае библиотека должна предоставить *package configuration file*. Путь с *package configuration file* должен быть указан в CMAKE\_PREFIX\_PATH при сборке проекта. Если `find_package` пакет был найден, то в окружении CMake создаются различные переменные, которые предоставляют информацию о найденном пакете. Переменные окружения описывают где находятся экспортируемые заголовочные файлы и исходные файлы пакетов, от каких библиотек зависит пакет, и где эти библиотеки находятся. Имена всегда имеют вид <имя пакета>\_<свойство>:

```
<NAME>_FOUND - Если библиотека найдена, то устанавливается в true, иначе - ошибка
<NAME>_INCLUDE_DIRS or <NAME>_INCLUDES - Пути к заголовочным файлам, экспортируемым пакетом
<NAME>_LIBRARIES or <NAME>_LIBS - Библиотеки, экспортируемые пакетом
<NAME>_DEFINITIONS - ? 
```

`gtest` можно установить при помощи [`vcpkg`](https://vcpkg.io/en/) ([подробнее](https://vcpkg.io/en/package/gtest)):

```pwsh
vcpkg install gtest
```

В классическом режиме `vcpkg` устанавливает пути поиска CMake соответствующим образом, чтобы сделать установленные пакеты доступными через `find_package()`, `find_library()` и `find_path()`.

```cmake
enable_testing()

...

add_test(NAME all_tests COMMAND gtest_program)
```

Сборка с CMake:

```pwsh
mkdir build; cd build

cmake .. -DCMAKE_TOOLCHAIN_FILE="$($env:VCPKG_ROOT)/scripts/buildsystems/vcpkg.cmake"

cmake --build .
```

`$($env:VCPKG_ROOT)` – переменная окружения с путём до `vcpkg`. Подробнее: [vcpkg in CMake projects](https://learn.microsoft.com/en-us/vcpkg/users/buildsystems/cmake-integration)

Добавляет тесты, которые будут запускаться после успешной сборки при вызове утилиты `ctest`.

При запуске собранного с тестами исполняемого файла (в примере выше – `gtest_program`) в поток вывода будут записаны логи тестирования:

```
.\build\Debug\gtest_program.exe
[==========] Running 5 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 5 tests from ctor
[ RUN      ] ctor.defaults
[       OK ] ctor.defaults (0 ms)
[ RUN      ] ctor.zero_float
[       OK ] ctor.zero_float (0 ms)
[ RUN      ] ctor.zero_double
[       OK ] ctor.zero_double (0 ms)
[ RUN      ] ctor.ctor_double
[       OK ] ctor.ctor_double (0 ms)
[ RUN      ] ctor.ctor_special
[       OK ] ctor.ctor_special (0 ms)
[----------] 5 tests from ctor (1 ms total)

[----------] Global test environment tear-down
[==========] 5 tests from 1 test suite ran. (2 ms total)
[  PASSED  ] 5 tests.
```

### Google Test Explorer for Visual Studio Code

В CMakeLists.txt напротив `add_tests` появится опция запуска/перезапуска тестов. Также в разделе Testing будут отображаться все найденные тесты:

![](/files/iYrnD3mDaqwykU7OeVTx)

### GoogleTest Adapter

Для использования данного расширения необходимо настроить `launch.json` с Debug-конфигурацией, например:

```json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(Debug) Launch",
            "type": "cppvsdbg",
            "request": "launch",
            "program": "./build/Debug/gtest_program.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "console": "externalTerminal"
        }

    ]
}
```

После чего по опции в Status bar (левая нижняя стрелка)

![](/files/hyVybIwD3aJCgL4CfsIs)

можно запустить исполняемый файл с тестами.

В Google Tests обозревателе будут отображаться найденные тесты по их группам:

![](/files/WgvotUze1jXNiwPY2peC)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skkv-itmo.gitbook.io/c-cpp-cookies/testing/gtest/gtest-vscode.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
