[{"data":1,"prerenderedAt":822},["ShallowReactive",2],{"/en-us/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci":3,"navigation-en-us":43,"banner-en-us":454,"footer-en-us":464,"blog-post-authors-en-us-Fatima Sarah Khalid":704,"blog-related-posts-en-us-develop-c-unit-testing-with-catch2-junit-and-gitlab-ci":718,"blog-promotions-en-us":760,"next-steps-en-us":812},{"id":4,"title":5,"authorSlugs":6,"authors":8,"body":10,"category":11,"categorySlug":11,"config":12,"content":16,"date":20,"description":17,"extension":27,"externalUrl":28,"featured":14,"heroImage":19,"isFeatured":14,"meta":29,"navigation":14,"path":30,"publishedDate":20,"rawbody":31,"seo":32,"slug":13,"stem":37,"tagSlugs":38,"tags":41,"template":15,"updatedDate":28,"__hash__":42},"blogPosts/en-us/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci.yml","Develop C++ unit testing with Catch2, JUnit, and GitLab CI",[7],"fatima-sarah-khalid",[9],"Fatima Sarah Khalid","Continuous integration (CI) and automated testing are important DevSecOps workflows for software developers to detect bugs early, improve code quality, and streamline their development processes.\nIn this tutorial, you'll learn how to set up unit testing on a `C++` project with [Catch2](https://github.com/catchorg/Catch2) and GitLab CI for continuous integration. You'll also see how the AI-powered features of [GitLab Duo](https://about.gitlab.com/gitlab-duo-agent-platform/) can help. We’ll use [an air quality monitoring application](https://gitlab.com/gitlab-da/use-cases/ai/ai-applications/air-quality-app) as our reference project.\n\n## Prerequisites\n\n- Ensure you have [CMake](https://cmake.org/ \"CMake\") installed on your machine. - A modern `C++` compiler such as GCC or Clang is required. - An API key from [OpenWeatherMap](https://openweathermap.org/api) - requires signing up for a free account (1,000/calls per day are included for free).\n## Set up the application for testing\n\nThe reference project we’ll be using for demonstrating testing in this blog post is an air quality monitoring application that fetches air quality data from the OpenWeatherMap API based on the U.S zip codes only provided by the user.\n\nHere are the steps to set up the application for testing:\n\n1. Fork the [the reference project](https://gitlab.com/gitlab-da/use-cases/ai/ai-applications/air-quality-app) and clone the fork to your local environment.\n\n2. Generate an API key from  [OpenWeatherMap](https://openweathermap.org/) and export it into the environment.\n```shell\nexport API_KEY=\"YOURAPIKEY_HERE\"\n```\n\n3. Alternatively, you can add the key into your `.env` configuration, and source it with `source ~/.env`, or use a different mechanism to populate the environment.\n\n4. Compile and build the project code with the following instructions:\n\n```cpp\ncmake -S . -B build\ncmake --build build\n```\n\n5. Run the application using the executable and passing in a U.S zip code (90210 as an example):\n```cpp\n./build/air_quality_app 90210\n```\n\nHere’s an example of what running the program will look like in your terminal: \n```bash\n❯ ./build/air_quality_app 90210\nAir Quality Index (AQI) for Zip Code 90210: 2 (Fair)\n```\n\n## Install Catch2\n\nNow that the application is set up and working, let's start working on adding testing using Catch2. Catch2 is a modern, `C++-native` testing framework for unit tests.\nYou can also ask GitLab Duo Chat within your IDE for an introduction to getting started with Catch2 as a `C++` testing framework. GitLab Duo Chat will provide getting started steps as well as an example test:\n![GitLab Duo Chat starting steps and example test](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676997/Blog/Content%20Images/1.duo-chat-installing-catch2.png)\n\n1. First navigate to your project’s root directory and create an externals folder using the `mkdir` command.\n\n```shell\nmkdir externals\n```\n\n2. There are several ways to install Catch2 via [its CMake integration](https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#top). We will use the option of installing it as a submodule and including it as part of the source code to simplify dependency management. To add Catch2 to your project in the `externals` folder:\n```shell\ngit submodule add https://github.com/catchorg/Catch2.git externals/Catch2\ngit submodule update --init --recursive\n```\n\n3. Update `CMakeLists.txt` to include Catch2’s directory as a subdirectory. This allows CMake to find and build Catch2 as a part of our project.\n```cpp\n# Assuming Catch2 in externals/Catch2\nadd_subdirectory(externals/Catch2)\n```\n\n4. Create a `tests.cpp` file in your project root to write our tests to:\n```shell\ntouch tests.cpp\n```\n\n5. Update `CMakeLists.txt` Link against Catch2. When defining your test executable in CMake, link it against Catch2:\n\n```cpp\n# Add tests executable and link it to Catch2\nadd_executable(tests test.cpp)\ntarget_link_libraries(tests PRIVATE Catch2::Catch2WithMain)\n```\n\n## Structure the project for testing\n\nBefore we start writing our tests, we should separate our application logic into separate files in order to maintain and test our code more efficiently. At the end of this section we should have:\n\n```text\nmain.cpp containing only the main() function and application setup\nincludes/functions.cpp containing all functional code such as API calls and data processing: includes/functions.h containing the declarations for the functions defined in functions.cpp.  It needs to define the preprocessor macro guards, and include all necessary headers. ```\n\nApply the following changes to the files:\n1. `main.cpp`\n\n```cpp\n#include \u003Ciostream>\n#include \"functions.h\"\n\nint main(int argc, char* argv[]) {\n   if (argc \u003C 2) {\n       std::cerr \u003C\u003C \"Usage: \" \u003C\u003C argv[0] \u003C\u003C \" \u003CZip Code>\" \u003C\u003C std::endl;\n       return 1;\n   }\n\n   std::string zipCode = argv[1];\n   std::string apiKey = getApiKey();\n   if (apiKey.empty()) {\n       std::cerr \u003C\u003C \"API key not found.\" \u003C\u003C std::endl;\n       return 1;\n   }\n\n   auto [lat, lon] = geocodeZipcode(zipCode, apiKey);\n   if (lat == 0 && lon == 0) {\n       std::cerr \u003C\u003C \"Failed to geocode zipcode.\" \u003C\u003C std::endl;\n       return 1;\n   }\n\n   std::string response = fetchAirQuality(lat, lon, apiKey);\n   std::string airQualityInfo = parseAirQualityResponse(response);\n\n   std::cout \u003C\u003C \"Air Quality Index for Zip Code \" \u003C\u003C zipCode \u003C\u003C \": \" \u003C\u003C airQualityInfo \u003C\u003C std::endl;\n\n   return 0;\n}\n```\n\n2. Create a `functions.h:` in the `includes` folder:\n```cpp\n#ifndef FUNCTIONS_H\n#define FUNCTIONS_H\n\n#include \u003Cstring>\n#include \u003Cutility>\n#include \u003Cvector>\n\n// Declare the function prototype\nstd::string httpRequest(const std::string& url);\nbool loadEnvFile(const std::string& filename);\nstd::string getApiKey();\nstd::pair\u003Cdouble, double> geocodeZipcode(const std::string& zipCode, const std::string& apiKey);\nstd::string fetchAirQuality(double lat, double lon, const std::string& apiKey);\nstd::string parseAirQualityResponse(const std::string& response);\n\n#endif\n```\n\n3. Create a `functions.cpp` in the `includes` folder:\n```cpp\n#include \"functions.h\"\n#include \u003Cfstream>\n#include \u003Celnormous/HTTPRequest.hpp>\n#include \u003Cnlohmann/json.hpp>\n#include \u003Ciostream>\n#include \u003Ccstdlib> // For getenv\n\nstd::string httpRequest(const std::string& url) {\n   try {\n       http::Request request{url};\n       const auto response = request.send(\"GET\");\n       return std::string{response.body.begin(), response.body.end()};\n   } catch (const std::exception& e) {\n       std::cerr \u003C\u003C \"Request failed, error: \" \u003C\u003C e.what() \u003C\u003C std::endl;\n       return \"\";\n   }\n}\nstd::string getApiKey() {\n   const char* envApiKey = std::getenv(\"API_KEY\");\n   if (envApiKey) {\n       return std::string(envApiKey);\n   }\n   // If the environment variable is not set, fallback to the config file\n   std::ifstream configFile(\"config.txt\");\n   std::string line;\n   if (getline(configFile, line)) {\n       return line.substr(line.find('=') + 1);\n   }\n   return \"\";\n}\n\nstd::pair\u003Cdouble, double> geocodeZipcode(const std::string& zipCode, const std::string& apiKey) {\n   std::string url = \"http://api.openweathermap.org/geo/1.0/zip?zip=\" + zipCode + \",US&appid=\" + apiKey;\n   std::string response = httpRequest(url);\n   try {\n       auto json = nlohmann::json::parse(response);\n       if (json.contains(\"lat\") && json.contains(\"lon\")) {\n           double lat = json[\"lat\"];\n           double lon = json[\"lon\"];\n           return {lat, lon};\n       } else {\n           std::cerr \u003C\u003C \"Geocode response missing 'lat' or 'lon' fields: \" \u003C\u003C response \u003C\u003C std::endl;\n       }\n   } catch (const nlohmann::json::parse_error& e) {\n       std::cerr \u003C\u003C \"Failed to parse geocode response: \" \u003C\u003C e.what() \u003C\u003C \" - Response: \" \u003C\u003C response \u003C\u003C std::endl;\n   }\n   return {0, 0};\n}\n\nstd::string fetchAirQuality(double lat, double lon, const std::string& apiKey) {\n   std::string url = \"http://api.openweathermap.org/data/2.5/air_pollution?lat=\" + std::to_string(lat) + \"&lon=\" + std::to_string(lon) + \"&appid=\" + apiKey;\n   std::string response = httpRequest(url);\n   return response;\n}\n\nstd::string parseAirQualityResponse(const std::string& response) {\n   try {\n       auto json = nlohmann::json::parse(response);\n       if (json.contains(\"list\") && !json[\"list\"].empty() && json[\"list\"][0].contains(\"main\")) {\n           int aqi = json[\"list\"][0][\"main\"][\"aqi\"];\n           std::string aqiCategory;\n           switch (aqi) {\n               case 1:\n                   aqiCategory = \"Good\";\n                   break;\n               case 2:\n                   aqiCategory = \"Fair\";\n                   break;\n               case 3:\n                   aqiCategory = \"Moderate\";\n                   break;\n               case 4:\n                   aqiCategory = \"Poor\";\n                   break;\n               case 5:\n                   aqiCategory = \"Very Poor\";\n                   break;\n               default:\n                   aqiCategory = \"Unknown\";\n                   break;\n           }\n           return std::to_string(aqi) + \" (\" + aqiCategory + \")\";\n       } else {\n           return \"No AQI data available\";\n       }\n   } catch (const std::exception& e) {\n       std::cerr \u003C\u003C \"Failed to parse JSON response: \" \u003C\u003C e.what() \u003C\u003C std::endl;\n       return \"Error parsing AQI data\";\n   }\n}\n\n```\n\n4. Now that we have separated the source files, we also need to update our `CMakeLists.txt` to include `functions.cpp` in the `add_executable()` calls:\n\n```cpp\ncmake_minimum_required(VERSION 3.14)\nproject(air-quality-app)\n\n# Set the C++ standard for the project\nset(CMAKE_CXX_STANDARD 17)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\ninclude_directories(${CMAKE_SOURCE_DIR}/includes)\n\n# Define the main program executable\nadd_executable(air_quality_app main.cpp includes/functions.cpp)\n\n# Assuming Catch2 in externals/Catch2\nadd_subdirectory(externals/Catch2)\n\n# Add tests executable and link it to Catch2\nadd_executable(tests tests.cpp includes/functions.cpp)\ntarget_link_libraries(tests PRIVATE Catch2::Catch2WithMain)\n```\n\nTo verify that the changes are working, regenerate the CMake configuration and rebuild the source code with the following commands. The build will take longer now that we're compiling Catch2 files.\n```shell\nrm -rf build # delete existing build files\ncmake -S . -B build cmake --build build  ```\n\nYou should be able to run the application without any errors.\n\n```shell\n./build/air_quality_app 90210\n```\n\n## Write tests in Catch2 \nCatch2 tests are made up of [macros and assertions](https://github.com/catchorg/Catch2/blob/devel/docs/assertions.md). Macros in Catch2 are used to define test cases and sections within those test cases. They help in organizing and structuring the tests. Assertions are used to verify that the code behaves as expected. If an assertion fails, the test case will fail, and Catch2 will report the failure.\n\nLet’s review a basic test scenario for an addition function to understand. Note: This test is read-only, as an example.\n```cpp\nint add(int a, int b) {\n   return a + b;\n}\n\nTEST_CASE(\"Addition works correctly\", \"[math]\") {\n   REQUIRE(add(1, 1) == 2);  // Test passes if 1+1 equals 2\n   REQUIRE(add(2, 2) != 5);  // Test passes if 2+2 does not equal 5\n}\n```\n\n- Each test begins with the `TEST_CASE` macro, which defines a test case container. The macro accepts two parameters: a string describing the test case and optionally a second string for tagging the test for easy filtering.\n- Tests are also composed of assertions, which are statements that check if conditions are true. Catch2 provides macros for assertion that include `REQUIRE`, which aborts the current test if the assertion fails, and `CHECK`, which logs the failure but continues with the current test.\n\n### Prepare to write tests with Catch2\n\nTo test the API retrieval functions in our air quality application, we’ll be using mock API requests. Mock API testing is a technique used to test how your application will interact with an external API without making any real API calls. Instead of sending requests to a live API server, we can simulate the responses using predefined data. Mock requests allow us to control the input data and specify exactly what the API would return for different requests, making sure that our tests aren't affected by changes in the real API responses or unexpected data. This also makes it easier for us to simulate and catch different failures.\n\nIn our `tests.cpp` file, let’s define the following function to run mock API requests.  \n```cpp\n#include \"includes/functions.h\"\n#include \u003Ccatch2/catch_test_macros.hpp>\n#include \u003Cstring>\n\n// Mock HTTP request function that simulates API responses\nstd::string mockHttpRequest(const std::string& url) {\n   if (url.find(\"geo\") != std::string::npos) {\n       // Mock response for geocoding\n       return R\"({\"lat\": 40.7128, \"lon\": -74.0060})\";    } else if (url.find(\"air_pollution\") != std::string::npos) {\n       // Mock response for air quality\n       return R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\";\n   }\n   // Default mock response for unmatched endpoints\n   return \"{}\";\n}\n// Overriding the actual httpRequest function with the mockHttpRequest for testing\nstd::string httpRequest(const std::string& url) {\n   return mockHttpRequest(url);\n}\n```\n\n- This function simulates HTTP requests and returns predefined JSON responses based on the URL given as input. - It also checks the URL to determine which type of data is being requested based on the functionality of the application (geocoding, air pollution, or forecast data). If the URL doesn’t match the expected endpoint, it returns an empty JSON object.\nDon't compile the code just yet, as you'll see a linker error. Since we're overriding the original `httpRequest` function with our mock function for testing, we'll need a preprocessor macro to enable conditional compilation - indicating which `httpRequest` function should run when we're compiling tests.\n#### Define a preprocessor macro for testing \nBecause we’ve overridden `httpRequest` in our `tests.cpp`, we need to exclude that code from `functions.cpp` when we’re testing. When building tests, we may need to ensure that certain parts of our code behave differently or are excluded. We can do this by defining a preprocessor macro `TESTING` which enables conditional compilation, allowing us to selectively include or exclude code when compiling the test target: \nWe define the `TESTING` macro in our `CMakeLists.txt` at the end: \n```cpp\n# Define TESTING macro for this target\ntarget_compile_definitions(tests PRIVATE TESTING)\n```\n\nAnd add the macro wrapper in  `functions.cpp` around the original `httpRequest` function: \n```cpp\n#ifndef TESTING  // Exclude this part when TESTING is defined\nstd::string httpRequest(const std::string& url) {\n   try {\n       http::Request request{url};\n       const auto response = request.send(\"GET\");\n       return std::string{response.body.begin(), response.body.end()};\n   } catch (const std::exception& e) {\n       std::cerr \u003C\u003C \"Request failed, error: \" \u003C\u003C e.what() \u003C\u003C std::endl;\n       return \"\";\n   }\n}\n#endif\n```\n\nRegenerate the CMake configuration and rebuild the source code to verify it works.\n\n```shell\ncmake --build build  ```\n\n### Write the first tests\nNow, let’s write some tests for our air quality application.\n\n#### Test 1: Verify API key retrieval\nThis test ensures that the `getApiKey` function retrieves the API key correctly from the environment variable or the configuration file. Add the test case to our `tests.cpp`:\n\n```cpp\n\nTEST_CASE(\"API Key Retrieval\", \"[api]\") {\n   // Set the API_KEY environment variable for testing\n   setenv(\"API_KEY\", \"test_key\", 1);\n   // Test if the key is retrieved correctly\n   REQUIRE(getApiKey() == \"test_key\");\n}\n```\n\nYou can verify that this tests passes by rebuilding the code and running the tests:\n\n```shell\ncmake --build build\n./build/tests\n```\n\n#### Test 2: Geocode the zip code\n\nThis test ensures that the `geocodeZipcode` function returns the correct latitude and longitude for a given zip code using the mock API response function we set up earlier. The  `geocodeZipcode` function is supposed to hit an API that returns geographic coordinates based on a zip code.\nIn `tests.cpp`, add this test case for the zip code 90210:\n```cpp\nTEST_CASE(\"Geocode Zip code\", \"[geocode]\") {\n   std::string apiKey = \"test_key\";\n   std::pair\u003Cdouble, double> coordinates = geocodeZipcode(\"90210\", apiKey);\n   // Check latitude\n   REQUIRE(coordinates.first == 40.7128);\n   // Check longitude    REQUIRE(coordinates.second == -74.0060);\n}\n```\n\nThe purpose of this test is to verify that the function `geocodeZipcode` can correctly parse the latitude and longitude from the API response. By hardcoding the expected response, we ensure that the test environment is controlled and predictable.\n\n #### Test 3: Air quality API test\n\nThis test ensures that the `fetchAirQuality` function correctly fetches air quality data using the mock API response function we set up earlier. It verifies that the function constructs the API request properly, sends it, and accurately parses the air quality index (AQI) from the mock JSON response. This validation helps ensure that the overall process of fetching and interpreting air quality data works as intended.\n\n```cpp\nTEST_CASE(\"Fetch Air Quality\", \"[airquality]\") {\n   std::string apiKey = \"test_key\";\n   double lat = 40.7128;\n   double lon = -74.0060;\n   std::string response = fetchAirQuality(lat, lon, apiKey);\n   // Check the response\n   REQUIRE(response == R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\");\n}\n```\n\n## Build and run the tests\n\nTo  build and compile our application, we'll use the same CMake commands as before:\n\n```cpp\ncmake -S . -B build\ncmake --build build\n\n```\n\nAfter building, we can run our tests by executing the test binary: \n```cpp\n./build/tests\n\n```\n\nRunning this command will execute all defined tests, and you will see output indicating whether each test has passed or failed.\n\n![Output showing pass/fail of tests](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/Blog/Content%20Images/2.running-catch2-tests.png)\n\n## Set up GitLab CI/CD\n\nTo automate the testing process each time we push some new code to our repository, let’s set up [GitLab CI/CD](https://about.gitlab.com/topics/ci-cd/). Create a new `.gitlab-ci.yml` configuration file in the root directory.\n```yaml\nimage: gcc:latest\n\nvariables:\n GIT_SUBMODULE_STRATEGY: recursive\n\nstages:\n - build\n - test\n\nbefore_script:\n - apt-get update && apt-get install -y cmake\n\ncompile:\n stage: build\n script:\n   - cmake -S . -B build\n   - cmake --build build\n artifacts:\n   paths:\n     - build/\n\ntest:\n stage: test\n script:\n   - ./build/tests --reporter junit -o test-results.xml\n artifacts:\n   reports:\n     junit: test-results.xml\n```\n\nThis CI/CD configuration will compile both the main application and the test suite, then run the tests, generating a JUnit XML report which GitLab uses to display the test results. \n- In `before_script`, we added an installation for `cmake`, and `git submodule sync --recursive` which initializes and updates our submodules (catch2). - In the `test` stage, `--reporter junit -o test-results.xml` specifies that the test results should be treated as a JUnit report which allows GitLab CI to display results in the UI. This is super helpful when you have several tests in your application. \nWe also need to [add an environmental variable](https://docs.gitlab.com/ci/variables/#define-a-cicd-variable-in-the-ui) with the `API_KEY` in project settings on GitLab.\n\nDon’t forget to add all new files to Git, and commit and push the changes in a new MR:\n\n```shell\ngit checkout -b tests-catch2-cicd\n\ngit add includes/functions.{h,cpp} tests.cpp .gitlab-ci.yml git add CMakeLists.txt main.cpp\ngit commit -vm “Add Catch2 tests and CI/CD configuration”\ngit push ```\n\n## View the test report\n\nAfter pushing our code changes, we can review the results of our tests in the GitLab UI in the Pipeline view in the `Tests` tab:\n\n![GitLab pipeline view shows test results](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/Blog/Content%20Images/2.0-passed-tests-UI.png)\n\n## Simulate a test failure\n\nTo demonstrate how our UI will handle test failures, we can intentionally introduce a bug into our code and observe the resulting behavior.\nLet's modify our `parseAirQualityResponse` function to introduce an error. We can change the AQI category for an AQI value of 2 from \"Fair\" to \"Poor.\" This change will cause the related test to fail, allowing us to see the test failure in the GitLab UI.\n\nIn `functions.cpp`, find the `parseAirQualityResponse` function and modify the switch statement for case `2` to set the `Poor` value instead of `Fair`:\n\n```cpp\n               // Intentional bug:\n               case 2:\n                   aqiCategory = \"Poor\";\n                   break;\n```\n\nIn tests.cpp, add a new test case that directly checks the output of the `parseAirQualityResponse` function. This test ensures that the `parseAirQualityResponse` function correctly parses and categorizes the air quality data from the mock API response. This function takes a JSON response, extracts the AQI value, and translates it into a human-readable category.\n\n```cpp\n\nTEST_CASE(\"Parse Air Quality Response\", \"[airquality]\") {\n   std::string mockResponse = R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\";\n   std::string result = parseAirQualityResponse(mockResponse);\n   // This should fail due to the intentional bug\n   REQUIRE(result == \"2 (Fair)\");\n}\n\n```\n\nCommit the changes, and push them into the MR. Open the MR in your browser.\nBy introducing an intentional bug in this function, we can see how a test failure is reported in GitLab's pipelines UI. We must add, commit, and push the changes to our repository to view the test failure in the pipeline.\n![Simulated test failure](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/Blog/Content%20Images/2.1-failed-test-simulation.png)\n\n![Details of the simulated failed test](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/Blog/Content%20Images/2.2-failed-test-simulation-details.png)\n\nOnce we've verified this simulated test failure, we can use `git revert` to roll back that commit.\n```shell\ngit revert\n```\n\n## Add and test a new feature\n\nLet’s put what you've learned together by creating a new feature in the air quality application and then writing a test for that feature using Catch2. The new feature will fetch the current weather forecast for the provided zip code.\n\nFirst, we'll define a `Weather` struct and add the function prototype in our `functions.h` file (inside the `#endif`):\n\n```cpp\n\nstruct Weather {\n   std::string main;\n   std::string description;\n   double temperature;\n};\n\nWeather getCurrentWeather(const std::string& apiKey, double lat, double lon);\n```\n\nThen, we implement the `getCurrentWeather` function in `functions.cpp`. This function calls the OpenWeatherMap API to retrieve the current weather and parses the JSON response. This code was generated using [GitLab Duo](https://about.gitlab.com/gitlab-duo-agent-platform/). If you start typing `Weather getCurrentWeather(const std::string& apiKey, double lat, double lon) {` to complete the function, GitLab Duo will provide the function contents for you, line by line.\n![GitLab Duo completing the function contents](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/Blog/Content%20Images/3.get-current-weather-function-completion.png)\n\nHere's what your `getCurrentWeather()` function can look like:\n```cpp\n\nWeather getCurrentWeather(const std::string& apiKey, double lat, double lon) {\n   std::string url = \"http://api.openweathermap.org/data/2.5/weather?lat=\" + std::to_string(lat) + \"&lon=\" + std::to_string(lon) + \"&appid=\" + apiKey;\n   std::string response = httpRequest(url);\n   auto json = nlohmann::json::parse(response);\n   Weather weather;\n   if (!json.is_null()) {\n       weather.main = json[\"weather\"][0][\"main\"];\n       weather.description = json[\"weather\"][0][\"description\"];\n       weather.temperature = json[\"main\"][\"temp\"];\n   }\n   return weather;\n}\n```\n\nAnd, finally, we update our `main.cpp` file in the main function to output the current forecast (and converting Kelvin to Celsius for the output): \n```cpp\n   Weather currentWeather = getCurrentWeather(apiKey, lat, lon);\n   if (currentWeather.main.empty()) {\n       std::cerr \u003C\u003C \"Failed to fetch current weather.\" \u003C\u003C std::endl;\n       return 1;\n   }\n\n   std::cout \u003C\u003C \"Current Weather: \" \u003C\u003C currentWeather.main \u003C\u003C \", \" \u003C\u003C currentWeather.description\n       \u003C\u003C \", temperature \" \u003C\u003C currentWeather.temperature - 273.15 \u003C\u003C \" °C\" \u003C\u003C std::endl;\n```\n\nWe can confirm that our new feature is working by building and running the application: \n```shell\ncmake --build build\n./build/air_quality_app ```\n\nAnd we should see the following output or similar in case the weather is different on the day the code is run :)\n\n```text\nAir Quality Index for Zip Code 90210: 2 (Poor)\nCurrent Weather: Clouds, broken clouds, temperature 23.2 °C\n```\n\nWith all new functionality, there should be testing! We can also write a test to check whether the application is fetching and parsing a weather forecast correctly. This test checks that the function returns a list containing the correct number of forecast entries and that each entry has accurate data regarding time and temperature.\n\n```cpp\nTEST_CASE(\"Current Weather functionality\", \"[api]\") {\n   auto weather = getCurrentWeather(\"dummyApiKey\", 40.7128, -74.0060);\n   // Ensure main weather description is not empty\n   REQUIRE_FALSE(weather.main.empty());\n   // Validate that temperature is a reasonable value\n   REQUIRE(weather.temperature > 0); }\n```\n\nWe’ll also have to update our `mockHTTPRequest` function in `tests.cpp` to account for this new test. Modify the if-condition with a new else-if branch checking for the `weather` string in the URL: \n```cpp\n// Mock HTTP request function that simulates API responses\nstd::string mockHttpRequest(const std::string &url)\n{\n   if (url.find(\"geo\") != std::string::npos)\n   {\n       // Mock response for geocoding\n       return R\"({\"lat\": 40.7128, \"lon\": -74.0060})\";\n   }\n   else if (url.find(\"air_pollution\") != std::string::npos)\n   {\n       // Mock response for air quality\n       return R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\";\n   }\n   else if (url.find(\"weather\") != std::string::npos)\n   {\n       // Mock response for current weather\n       return R\"({\n          \"weather\": [{\"main\": \"Clear\", \"description\": \"clear sky\"}],\n          \"main\": {\"temp\": 298.55}\n      })\";\n   }\n   return \"{}\";\n}\n```\n\nAnd verify that our tests are working by rebuilding and running our tests: \n```shell\ncmake --build build ./build/tests\n```\n\nAll tests should pass, including the new one for Current Weather Functionality.\n## Optimize tests.cpp with sections\n\nTo better organize our tests as the project grows and categorize each functionality, we can use Catch2’s `SECTION` macro. The `SECTION` macro allows you to define logically separate test scenarios within a single test case, providing a clean way to test different behaviors or conditions without requiring multiple separate test cases or multiple files. This approach keeps related tests bundled together and also improves test maintainability by allowing shared setup code to be executed repeatedly for each section.\n\nSince some of our functionality is preprocessing data to retrieve information, let’s section our tests as such:\n- preprocessing steps: \t- API key validation\n\t- geocoding validation\n-  API data retrieval:\n\t- air pollution retrieval \t- forecast retrieval\n\nHere’s what our `tests.cpp` will look like if organized by sections:\n```cpp\n#include \"functions.h\"\n#include \u003Ccatch2/catch_test_macros.hpp>\n#include \u003Cstring>\n\n// Mock HTTP request function that simulates API responses\nstd::string mockHttpRequest(const std::string &url)\n{\n   if (url.find(\"geo\") != std::string::npos)\n   {\n       // Mock response for geocoding\n       return R\"({\"lat\": 40.7128, \"lon\": -74.0060})\";\n   }\n   else if (url.find(\"air_pollution\") != std::string::npos)\n   {\n       // Mock response for air quality\n       return R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\";\n   }\n   else if (url.find(\"weather\") != std::string::npos)\n   {\n       // Mock response for current weather\n       return R\"({\n          \"weather\": [{\"main\": \"Clear\", \"description\": \"clear sky\"}],\n          \"main\": {\"temp\": 298.55}\n      })\";\n   }\n   return \"{}\";\n}\n\n// Overriding the actual httpRequest function with the mockHttpRequest for testing\nstd::string httpRequest(const std::string &url)\n{\n   return mockHttpRequest(url);\n}\n\n// Preprocessing Steps\nTEST_CASE(\"Preprocessing Steps\", \"[preprocessing]\") {\n   SECTION(\"API Key Retrieval\") {\n       // Set the API_KEY environment variable for testing\n       setenv(\"API_KEY\", \"test_key\", 1);\n       // Test if the key is retrieved correctly\n       REQUIRE_FALSE(getApiKey().empty());\n   }\n\n   SECTION(\"Geocode Functionality\") {\n       std::string apiKey = \"test_key\";\n       std::pair\u003Cdouble, double> coordinates = geocodeZipcode(\"90210\", apiKey);\n       // Check latitude\n       REQUIRE(coordinates.first == 40.7128);\n       // Check longitude        REQUIRE(coordinates.second == -74.0060);\n   }\n}\n\n// API Data Retrieval\nTEST_CASE(\"API Data Retrieval\", \"[data_retrieval]\") {\n   SECTION(\"Air Quality Functionality\") {\n       std::string apiKey = \"test_key\";\n       double lat = 40.7128;\n       double lon = -74.0060;\n       std::string response = fetchAirQuality(lat, lon, apiKey);\n       // Check the response\n       REQUIRE(response == R\"({\"list\": [{\"main\": {\"aqi\": 2}}]})\");\n   }\n\n   SECTION(\"Current Weather Functionality\") {\n       auto weather = getCurrentWeather(\"dummyApiKey\", 40.7128, -74.0060);\n       // Ensure main weather description is not empty\n       REQUIRE_FALSE(weather.main.empty());\n       // Validate that temperature is a reasonable value\n       REQUIRE(weather.temperature > 0);\n   }\n}\n```\n\nRebuild the code and run the tests again to verify.\n\n```shell\ncmake --build build ./build/tests\n```\n\n## Next steps\n\nIn this post, we covered how to integrate unit testing into a `C++` project using Catch2 testing framework and GitLab CI/CD and set up basic tests for our reference air quality application project.\n\nTo explore these concepts further, you can check out the [Catch2 documentation](https://github.com/catchorg/Catch2) and [GitLab's Unit test report examples documentation](https://docs.gitlab.com/ci/testing/unit_test_report_examp/ les.html).\nFor an advanced async exercise, you could build upon this project by using GitLab Duo to implement a feature that retrieves and analyzes historical air quality data and add code quality checks into the CI/CD pipeline. Happy coding! \n","devsecops",{"slug":13,"featured":14,"template":15},"develop-c-unit-testing-with-catch2-junit-and-gitlab-ci",true,"BlogPost",{"title":5,"description":17,"authors":18,"heroImage":19,"date":20,"body":10,"category":11,"tags":21},"Learn how to set up, write, and automate C++ unit tests using Catch2 with GitLab CI/CD. See examples from a working air quality app project and AI-powered help from GitLab Duo.",[9],"https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659684/Blog/Hero%20Images/AdobeStock_479904468__1_.jpg","2024-07-02",[22,23,24,25,26],"tutorial","testing","CI","AI/ML","DevSecOps","yml",null,{},"/en-us/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci","seo:\n  title: Develop C++ unit testing with Catch2, JUnit, and GitLab CI\n  description: >-\n    Learn how to set up, write, and automate C++ unit tests using Catch2 with\n    GitLab CI/CD. See examples from a working air quality app project and\n    AI-powered help from GitLab Duo.\n  ogTitle: Develop C++ unit testing with Catch2, JUnit, and GitLab CI\n  ogDescription: >-\n    Learn how to set up, write, and automate C++ unit tests using Catch2 with\n    GitLab CI/CD. See examples from a working air quality app project and\n    AI-powered help from GitLab Duo.\n  noIndex: false\n  ogImage: >-\n    https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659684/Blog/Hero%20Images/AdobeStock_479904468__1_.jpg\n  ogUrl: >-\n    https://about.gitlab.com/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci\n  ogSiteName: https://about.gitlab.com\n  ogType: article\n  canonicalUrls: >-\n    https://about.gitlab.com/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci\ncontent:\n  title: Develop C++ unit testing with Catch2, JUnit, and GitLab CI\n  description: >-\n    Learn how to set up, write, and automate C++ unit tests using Catch2 with\n    GitLab CI/CD. See examples from a working air quality app project and\n    AI-powered help from GitLab Duo.\n  authors:\n    - Fatima Sarah Khalid\n  heroImage: >-\n    https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659684/Blog/Hero%20Images/AdobeStock_479904468__1_.jpg\n  date: '2024-07-02'\n  body: \"Continuous integration (CI) and automated testing are important DevSecOps\n    workflows for software developers to detect bugs early, improve code\n    quality, and streamline their development processes.\\\n\n\n    In this tutorial, you'll learn how to set up unit testing on a `C++` project\n    with [Catch2](https://github.com/catchorg/Catch2) and GitLab CI for\n    continuous integration. You'll also see how the AI-powered features of\n    [GitLab Duo](https://about.gitlab.com/gitlab-duo-agent-platform/) can help. We’ll use [an\n    air quality monitoring\n    application](https://gitlab.com/gitlab-da/use-cases/ai/ai-applications/air-\\\n    quality-app) as our reference project.\n\n\n    ## Prerequisites\n\n\n    - Ensure you have [CMake](https://cmake.org/ \\\"CMake\\\") installed on your\n    machine.\\\n\n    - A modern `C++` compiler such as GCC or Clang is required.\\\n\n    - An API key from [OpenWeatherMap](https://openweathermap.org/api) -\n    requires signing up for a free account (1,000/calls per day are included for\n    free).\\\n\n\n    ## Set up the application for testing\n\n\n    The reference project we’ll be using for demonstrating testing in this blog\n    post is an air quality monitoring application that fetches air quality data\n    from the OpenWeatherMap API based on the U.S zip codes only provided by the\n    user.\n\n\n    Here are the steps to set up the application for testing:\n\n\n    1. Fork the [the reference\n    project](https://gitlab.com/gitlab-da/use-cases/ai/ai-applications/air-qual\\\n    ity-app) and clone the fork to your local environment.\n\n\n    2. Generate an API key from  [OpenWeatherMap](https://openweathermap.org/)\n    and export it into the environment.\\\n\n\n    ```shell\n\n    export API_KEY=\\\"YOURAPIKEY_HERE\\\"\n\n    ```\n\n\n    3. Alternatively, you can add the key into your `.env` configuration, and\n    source it with `source ~/.env`, or use a different mechanism to populate the\n    environment.\n\n\n    4. Compile and build the project code with the following instructions:\n\n\n    ```cpp\n\n    cmake -S . -B build\n\n    cmake --build build\n\n    ```\n\n\n    5. Run the application using the executable and passing in a U.S zip code\n    (90210 as an example):\\\n\n\n    ```cpp\n\n    ./build/air_quality_app 90210\n\n    ```\n\n\n    Here’s an example of what running the program will look like in your\n    terminal: \\\n\n\n    ```bash\n\n    ❯ ./build/air_quality_app 90210\n\n    Air Quality Index (AQI) for Zip Code 90210: 2 (Fair)\n\n    ```\n\n\n    ## Install Catch2\n\n\n    Now that the application is set up and working, let's start working on\n    adding testing using Catch2. Catch2 is a modern, `C++-native` testing\n    framework for unit tests.\\\n\n\n    You can also ask GitLab Duo Chat within your IDE for an introduction to\n    getting started with Catch2 as a `C++` testing framework. GitLab Duo Chat\n    will provide getting started steps as well as an example test:\\\n\n\n    ![GitLab Duo Chat starting steps and example\n    test](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676997/\\\n    Blog/Content%20Images/1.duo-chat-installing-catch2.png)\n\n\n    1. First navigate to your project’s root directory and create an externals\n    folder using the `mkdir` command.\n\n\n    ```shell\n\n    mkdir externals\n\n    ```\n\n\n    2. There are several ways to install Catch2 via [its CMake\n    integration](https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integ\\\n    ration.md#top). We will use the option of installing it as a submodule and\n    including it as part of the source code to simplify dependency management.\n    To add Catch2 to your project in the `externals` folder:\\\n\n\n    ```shell\n\n    git submodule add https://github.com/catchorg/Catch2.git externals/Catch2\n\n    git submodule update --init --recursive\n\n    ```\n\n\n    3. Update `CMakeLists.txt` to include Catch2’s directory as a subdirectory.\n    This allows CMake to find and build Catch2 as a part of our project.\\\n\n\n    ```cpp\n\n    # Assuming Catch2 in externals/Catch2\n\n    add_subdirectory(externals/Catch2)\n\n    ```\n\n\n    4. Create a `tests.cpp` file in your project root to write our tests to:\\\n\n\n    ```shell\n\n    touch tests.cpp\n\n    ```\n\n\n    5. Update `CMakeLists.txt` Link against Catch2. When defining your test\n    executable in CMake, link it against Catch2:\n\n\n    ```cpp\n\n    # Add tests executable and link it to Catch2\n\n    add_executable(tests test.cpp)\n\n    target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)\n\n    ```\n\n\n    ## Structure the project for testing\n\n\n    Before we start writing our tests, we should separate our application logic\n    into separate files in order to maintain and test our code more efficiently.\n    At the end of this section we should have:\n\n\n    ```text\n\n    main.cpp containing only the main() function and application setup\n\n    includes/functions.cpp containing all functional code such as API calls and\n    data processing:\\\n\n    includes/functions.h containing the declarations for the functions defined\n    in functions.cpp.  It needs to define the preprocessor macro guards, and\n    include all necessary headers.\\\n\n    ```\n\n\n    Apply the following changes to the files:\\\n\n\n    1. `main.cpp`\n\n\n    ```cpp\n\n    #include \u003Ciostream>\n\n    #include \\\"functions.h\\\"\n\n\n    int main(int argc, char* argv[]) {\n\n    \\   if (argc \u003C 2) {\n\n    \\       std::cerr \u003C\u003C \\\"Usage: \\\" \u003C\u003C argv[0] \u003C\u003C \\\" \u003CZip Code>\\\" \u003C\u003C std::endl;\n\n    \\       return 1;\n\n    \\   }\n\n\n    \\   std::string zipCode = argv[1];\n\n    \\   std::string apiKey = getApiKey();\n\n    \\   if (apiKey.empty()) {\n\n    \\       std::cerr \u003C\u003C \\\"API key not found.\\\" \u003C\u003C std::endl;\n\n    \\       return 1;\n\n    \\   }\n\n\n    \\   auto [lat, lon] = geocodeZipcode(zipCode, apiKey);\n\n    \\   if (lat == 0 && lon == 0) {\n\n    \\       std::cerr \u003C\u003C \\\"Failed to geocode zipcode.\\\" \u003C\u003C std::endl;\n\n    \\       return 1;\n\n    \\   }\n\n\n    \\   std::string response = fetchAirQuality(lat, lon, apiKey);\n\n    \\   std::string airQualityInfo = parseAirQualityResponse(response);\n\n\n    \\   std::cout \u003C\u003C \\\"Air Quality Index for Zip Code \\\" \u003C\u003C zipCode \u003C\u003C \\\": \\\" \u003C\u003C\n    airQualityInfo \u003C\u003C std::endl;\n\n\n    \\   return 0;\n\n    }\n\n    ```\n\n\n    2. Create a `functions.h:` in the `includes` folder:\\\n\n\n    ```cpp\n\n    #ifndef FUNCTIONS_H\n\n    #define FUNCTIONS_H\n\n\n    #include \u003Cstring>\n\n    #include \u003Cutility>\n\n    #include \u003Cvector>\n\n\n    // Declare the function prototype\n\n    std::string httpRequest(const std::string& url);\n\n    bool loadEnvFile(const std::string& filename);\n\n    std::string getApiKey();\n\n    std::pair\u003Cdouble, double> geocodeZipcode(const std::string& zipCode, const\n    std::string& apiKey);\n\n    std::string fetchAirQuality(double lat, double lon, const std::string&\n    apiKey);\n\n    std::string parseAirQualityResponse(const std::string& response);\n\n\n    #endif\n\n    ```\n\n\n    3. Create a `functions.cpp` in the `includes` folder:\\\n\n\n    ```cpp\n\n    #include \\\"functions.h\\\"\n\n    #include \u003Cfstream>\n\n    #include \u003Celnormous/HTTPRequest.hpp>\n\n    #include \u003Cnlohmann/json.hpp>\n\n    #include \u003Ciostream>\n\n    #include \u003Ccstdlib> // For getenv\n\n\n    std::string httpRequest(const std::string& url) {\n\n    \\   try {\n\n    \\       http::Request request{url};\n\n    \\       const auto response = request.send(\\\"GET\\\");\n\n    \\       return std::string{response.body.begin(), response.body.end()};\n\n    \\   } catch (const std::exception& e) {\n\n    \\       std::cerr \u003C\u003C \\\"Request failed, error: \\\" \u003C\u003C e.what() \u003C\u003C std::endl;\n\n    \\       return \\\"\\\";\n\n    \\   }\n\n    }\n\n    std::string getApiKey() {\n\n    \\   const char* envApiKey = std::getenv(\\\"API_KEY\\\");\n\n    \\   if (envApiKey) {\n\n    \\       return std::string(envApiKey);\n\n    \\   }\n\n    \\   // If the environment variable is not set, fallback to the config file\n\n    \\   std::ifstream configFile(\\\"config.txt\\\");\n\n    \\   std::string line;\n\n    \\   if (getline(configFile, line)) {\n\n    \\       return line.substr(line.find('=') + 1);\n\n    \\   }\n\n    \\   return \\\"\\\";\n\n    }\n\n\n    std::pair\u003Cdouble, double> geocodeZipcode(const std::string& zipCode, const\n    std::string& apiKey) {\n\n    \\   std::string url = \\\"http://api.openweathermap.org/geo/1.0/zip?zip=\\\" +\n    zipCode + \\\",US&appid=\\\" + apiKey;\n\n    \\   std::string response = httpRequest(url);\n\n    \\   try {\n\n    \\       auto json = nlohmann::json::parse(response);\n\n    \\       if (json.contains(\\\"lat\\\") && json.contains(\\\"lon\\\")) {\n\n    \\           double lat = json[\\\"lat\\\"];\n\n    \\           double lon = json[\\\"lon\\\"];\n\n    \\           return {lat, lon};\n\n    \\       } else {\n\n    \\           std::cerr \u003C\u003C \\\"Geocode response missing 'lat' or 'lon' fields:\n    \\\" \u003C\u003C response \u003C\u003C std::endl;\n\n    \\       }\n\n    \\   } catch (const nlohmann::json::parse_error& e) {\n\n    \\       std::cerr \u003C\u003C \\\"Failed to parse geocode response: \\\" \u003C\u003C e.what() \u003C\u003C\n    \\\" - Response: \\\" \u003C\u003C response \u003C\u003C std::endl;\n\n    \\   }\n\n    \\   return {0, 0};\n\n    }\n\n\n    std::string fetchAirQuality(double lat, double lon, const std::string&\n    apiKey) {\n\n    \\   std::string url =\n    \\\"http://api.openweathermap.org/data/2.5/air_pollution?lat=\\\" +\n    std::to_string(lat) + \\\"&lon=\\\" + std::to_string(lon) + \\\"&appid=\\\" +\n    apiKey;\n\n    \\   std::string response = httpRequest(url);\n\n    \\   return response;\n\n    }\n\n\n    std::string parseAirQualityResponse(const std::string& response) {\n\n    \\   try {\n\n    \\       auto json = nlohmann::json::parse(response);\n\n    \\       if (json.contains(\\\"list\\\") && !json[\\\"list\\\"].empty() &&\n    json[\\\"list\\\"][0].contains(\\\"main\\\")) {\n\n    \\           int aqi = json[\\\"list\\\"][0][\\\"main\\\"][\\\"aqi\\\"];\n\n    \\           std::string aqiCategory;\n\n    \\           switch (aqi) {\n\n    \\               case 1:\n\n    \\                   aqiCategory = \\\"Good\\\";\n\n    \\                   break;\n\n    \\               case 2:\n\n    \\                   aqiCategory = \\\"Fair\\\";\n\n    \\                   break;\n\n    \\               case 3:\n\n    \\                   aqiCategory = \\\"Moderate\\\";\n\n    \\                   break;\n\n    \\               case 4:\n\n    \\                   aqiCategory = \\\"Poor\\\";\n\n    \\                   break;\n\n    \\               case 5:\n\n    \\                   aqiCategory = \\\"Very Poor\\\";\n\n    \\                   break;\n\n    \\               default:\n\n    \\                   aqiCategory = \\\"Unknown\\\";\n\n    \\                   break;\n\n    \\           }\n\n    \\           return std::to_string(aqi) + \\\" (\\\" + aqiCategory + \\\")\\\";\n\n    \\       } else {\n\n    \\           return \\\"No AQI data available\\\";\n\n    \\       }\n\n    \\   } catch (const std::exception& e) {\n\n    \\       std::cerr \u003C\u003C \\\"Failed to parse JSON response: \\\" \u003C\u003C e.what() \u003C\u003C\n    std::endl;\n\n    \\       return \\\"Error parsing AQI data\\\";\n\n    \\   }\n\n    }\n\n\n    ```\n\n\n    4. Now that we have separated the source files, we also need to update our\n    `CMakeLists.txt` to include `functions.cpp` in the `add_executable()` calls:\n\n\n    ```cpp\n\n    cmake_minimum_required(VERSION 3.14)\n\n    project(air-quality-app)\n\n\n    # Set the C++ standard for the project\n\n    set(CMAKE_CXX_STANDARD 17)\n\n    set(CMAKE_CXX_STANDARD_REQUIRED ON)\n\n    set(CMAKE_CXX_EXTENSIONS OFF)\n\n\n    include_directories(${CMAKE_SOURCE_DIR}/includes)\n\n\n    # Define the main program executable\n\n    add_executable(air_quality_app main.cpp includes/functions.cpp)\n\n\n    # Assuming Catch2 in externals/Catch2\n\n    add_subdirectory(externals/Catch2)\n\n\n    # Add tests executable and link it to Catch2\n\n    add_executable(tests tests.cpp includes/functions.cpp)\n\n    target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)\n\n    ```\n\n\n    To verify that the changes are working, regenerate the CMake configuration\n    and rebuild the source code with the following commands. The build will take\n    longer now that we're compiling Catch2 files.\\\n\n\n    ```shell\n\n    rm -rf build # delete existing build files\n\n    cmake -S . -B build\\\n\n    cmake --build build \\\n\n    ```\n\n\n    You should be able to run the application without any errors.\n\n\n    ```shell\n\n    ./build/air_quality_app 90210\n\n    ```\n\n\n    ## Write tests in Catch2 \\\n\n\n    Catch2 tests are made up of [macros and\n    assertions](https://github.com/catchorg/Catch2/blob/devel/docs/assertions.m\\\n    d). Macros in Catch2 are used to define test cases and sections within those\n    test cases. They help in organizing and structuring the tests. Assertions\n    are used to verify that the code behaves as expected. If an assertion fails,\n    the test case will fail, and Catch2 will report the failure.\n\n\n    Let’s review a basic test scenario for an addition function to understand.\n    Note: This test is read-only, as an example.\\\n\n\n    ```cpp\n\n    int add(int a, int b) {\n\n    \\   return a + b;\n\n    }\n\n\n    TEST_CASE(\\\"Addition works correctly\\\", \\\"[math]\\\") {\n\n    \\   REQUIRE(add(1, 1) == 2);  // Test passes if 1+1 equals 2\n\n    \\   REQUIRE(add(2, 2) != 5);  // Test passes if 2+2 does not equal 5\n\n    }\n\n    ```\n\n\n    - Each test begins with the `TEST_CASE` macro, which defines a test case\n    container. The macro accepts two parameters: a string describing the test\n    case and optionally a second string for tagging the test for easy filtering.\n\n    - Tests are also composed of assertions, which are statements that check if\n    conditions are true. Catch2 provides macros for assertion that include\n    `REQUIRE`, which aborts the current test if the assertion fails, and\n    `CHECK`, which logs the failure but continues with the current test.\n\n\n    ### Prepare to write tests with Catch2\n\n\n    To test the API retrieval functions in our air quality application, we’ll be\n    using mock API requests. Mock API testing is a technique used to test how\n    your application will interact with an external API without making any real\n    API calls. Instead of sending requests to a live API server, we can simulate\n    the responses using predefined data. Mock requests allow us to control the\n    input data and specify exactly what the API would return for different\n    requests, making sure that our tests aren't affected by changes in the real\n    API responses or unexpected data. This also makes it easier for us to\n    simulate and catch different failures.\n\n\n    In our `tests.cpp` file, let’s define the following function to run mock API\n    requests.  \\\n\n\n    ```cpp\n\n    #include \\\"includes/functions.h\\\"\n\n    #include \u003Ccatch2/catch_test_macros.hpp>\n\n    #include \u003Cstring>\n\n\n    // Mock HTTP request function that simulates API responses\n\n    std::string mockHttpRequest(const std::string& url) {\n\n    \\   if (url.find(\\\"geo\\\") != std::string::npos) {\n\n    \\       // Mock response for geocoding\n\n    \\       return R\\\"({\\\"lat\\\": 40.7128, \\\"lon\\\": -74.0060})\\\";\\\n\n    \\   } else if (url.find(\\\"air_pollution\\\") != std::string::npos) {\n\n    \\       // Mock response for air quality\n\n    \\       return R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\": 2}}]})\\\";\n\n    \\   }\n\n    \\   // Default mock response for unmatched endpoints\n\n    \\   return \\\"{}\\\";\n\n    }\n\n    // Overriding the actual httpRequest function with the mockHttpRequest for\n    testing\n\n    std::string httpRequest(const std::string& url) {\n\n    \\   return mockHttpRequest(url);\n\n    }\n\n    ```\n\n\n    - This function simulates HTTP requests and returns predefined JSON\n    responses based on the URL given as input.\\\n\n    - It also checks the URL to determine which type of data is being requested\n    based on the functionality of the application (geocoding, air pollution, or\n    forecast data). If the URL doesn’t match the expected endpoint, it returns\n    an empty JSON object.\\\n\n\n    Don't compile the code just yet, as you'll see a linker error. Since we're\n    overriding the original `httpRequest` function with our mock function for\n    testing, we'll need a preprocessor macro to enable conditional compilation -\n    indicating which `httpRequest` function should run when we're compiling\n    tests.\\\n\n\n    #### Define a preprocessor macro for testing \\\n\n\n    Because we’ve overridden `httpRequest` in our `tests.cpp`, we need to\n    exclude that code from `functions.cpp` when we’re testing. When building\n    tests, we may need to ensure that certain parts of our code behave\n    differently or are excluded. We can do this by defining a preprocessor macro\n    `TESTING` which enables conditional compilation, allowing us to selectively\n    include or exclude code when compiling the test target: \\\n\n\n    We define the `TESTING` macro in our `CMakeLists.txt` at the end: \\\n\n\n    ```cpp\n\n    # Define TESTING macro for this target\n\n    target_compile_definitions(tests PRIVATE TESTING)\n\n    ```\n\n\n    And add the macro wrapper in  `functions.cpp` around the original\n    `httpRequest` function: \\\n\n\n    ```cpp\n\n    #ifndef TESTING  // Exclude this part when TESTING is defined\n\n    std::string httpRequest(const std::string& url) {\n\n    \\   try {\n\n    \\       http::Request request{url};\n\n    \\       const auto response = request.send(\\\"GET\\\");\n\n    \\       return std::string{response.body.begin(), response.body.end()};\n\n    \\   } catch (const std::exception& e) {\n\n    \\       std::cerr \u003C\u003C \\\"Request failed, error: \\\" \u003C\u003C e.what() \u003C\u003C std::endl;\n\n    \\       return \\\"\\\";\n\n    \\   }\n\n    }\n\n    #endif\n\n    ```\n\n\n    Regenerate the CMake configuration and rebuild the source code to verify it\n    works.\n\n\n    ```shell\n\n    cmake --build build \\\n\n    ```\n\n\n    ### Write the first tests\\\n\n\n    Now, let’s write some tests for our air quality application.\n\n\n    #### Test 1: Verify API key retrieval\\\n\n\n    This test ensures that the `getApiKey` function retrieves the API key\n    correctly from the environment variable or the configuration file. Add the\n    test case to our `tests.cpp`:\n\n\n    ```cpp\n\n\n    TEST_CASE(\\\"API Key Retrieval\\\", \\\"[api]\\\") {\n\n    \\   // Set the API_KEY environment variable for testing\n\n    \\   setenv(\\\"API_KEY\\\", \\\"test_key\\\", 1);\n\n    \\   // Test if the key is retrieved correctly\n\n    \\   REQUIRE(getApiKey() == \\\"test_key\\\");\n\n    }\n\n    ```\n\n\n    You can verify that this tests passes by rebuilding the code and running the\n    tests:\n\n\n    ```shell\n\n    cmake --build build\n\n    ./build/tests\n\n    ```\n\n\n    #### Test 2: Geocode the zip code\n\n\n    This test ensures that the `geocodeZipcode` function returns the correct\n    latitude and longitude for a given zip code using the mock API response\n    function we set up earlier. The  `geocodeZipcode` function is supposed to\n    hit an API that returns geographic coordinates based on a zip code.\\\n\n\n    In `tests.cpp`, add this test case for the zip code 90210:\\\n\n\n    ```cpp\n\n    TEST_CASE(\\\"Geocode Zip code\\\", \\\"[geocode]\\\") {\n\n    \\   std::string apiKey = \\\"test_key\\\";\n\n    \\   std::pair\u003Cdouble, double> coordinates = geocodeZipcode(\\\"90210\\\",\n    apiKey);\n\n    \\   // Check latitude\n\n    \\   REQUIRE(coordinates.first == 40.7128);\n\n    \\   // Check longitude\\\n\n    \\   REQUIRE(coordinates.second == -74.0060);\n\n    }\n\n    ```\n\n\n    The purpose of this test is to verify that the function `geocodeZipcode` can\n    correctly parse the latitude and longitude from the API response. By\n    hardcoding the expected response, we ensure that the test environment is\n    controlled and predictable.\n\n\n    \\ #### Test 3: Air quality API test\n\n\n    This test ensures that the `fetchAirQuality` function correctly fetches air\n    quality data using the mock API response function we set up earlier. It\n    verifies that the function constructs the API request properly, sends it,\n    and accurately parses the air quality index (AQI) from the mock JSON\n    response. This validation helps ensure that the overall process of fetching\n    and interpreting air quality data works as intended.\n\n\n    ```cpp\n\n    TEST_CASE(\\\"Fetch Air Quality\\\", \\\"[airquality]\\\") {\n\n    \\   std::string apiKey = \\\"test_key\\\";\n\n    \\   double lat = 40.7128;\n\n    \\   double lon = -74.0060;\n\n    \\   std::string response = fetchAirQuality(lat, lon, apiKey);\n\n    \\   // Check the response\n\n    \\   REQUIRE(response == R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\": 2}}]})\\\");\n\n    }\n\n    ```\n\n\n    ## Build and run the tests\n\n\n    To  build and compile our application, we'll use the same CMake commands as\n    before:\n\n\n    ```cpp\n\n    cmake -S . -B build\n\n    cmake --build build\n\n\n    ```\n\n\n    After building, we can run our tests by executing the test binary: \\\n\n\n    ```cpp\n\n    ./build/tests\n\n\n    ```\n\n\n    Running this command will execute all defined tests, and you will see output\n    indicating whether each test has passed or failed.\n\n\n    ![Output showing pass/fail of\n    tests](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998\\\n    /Blog/Content%20Images/2.running-catch2-tests.png)\n\n\n    ## Set up GitLab CI/CD\n\n\n    To automate the testing process each time we push some new code to our\n    repository, let’s set up [GitLab\n    CI/CD](https://about.gitlab.com/topics/ci-cd/). Create a new\n    `.gitlab-ci.yml` configuration file in the root directory.\\\n\n\n    ```yaml\n\n    image: gcc:latest\n\n\n    variables:\n\n    \\ GIT_SUBMODULE_STRATEGY: recursive\n\n\n    stages:\n\n    \\ - build\n\n    \\ - test\n\n\n    before_script:\n\n    \\ - apt-get update && apt-get install -y cmake\n\n\n    compile:\n\n    \\ stage: build\n\n    \\ script:\n\n    \\   - cmake -S . -B build\n\n    \\   - cmake --build build\n\n    \\ artifacts:\n\n    \\   paths:\n\n    \\     - build/\n\n\n    test:\n\n    \\ stage: test\n\n    \\ script:\n\n    \\   - ./build/tests --reporter junit -o test-results.xml\n\n    \\ artifacts:\n\n    \\   reports:\n\n    \\     junit: test-results.xml\n\n    ```\n\n\n    This CI/CD configuration will compile both the main application and the test\n    suite, then run the tests, generating a JUnit XML report which GitLab uses\n    to display the test results. \\\n\n\n    - In `before_script`, we added an installation for `cmake`, and `git\n    submodule sync --recursive` which initializes and updates our submodules\n    (catch2).\\\n\n    - In the `test` stage, `--reporter junit -o test-results.xml` specifies that\n    the test results should be treated as a JUnit report which allows GitLab CI\n    to display results in the UI. This is super helpful when you have several\n    tests in your application. \\\n\n\n    We also need to [add an environmental\n    variable](https://docs.gitlab.com/ci/variables/#define-a-cicd-variable-i\\\n    n-the-ui) with the `API_KEY` in project settings on GitLab.\n\n\n    Don’t forget to add all new files to Git, and commit and push the changes in\n    a new MR:\n\n\n    ```shell\n\n    git checkout -b tests-catch2-cicd\n\n\n    git add includes/functions.{h,cpp} tests.cpp .gitlab-ci.yml\\\n\n    git add CMakeLists.txt main.cpp\\\n\n\n    git commit -vm “Add Catch2 tests and CI/CD configuration”\n\n    git push\\\n\n    ```\n\n\n    ## View the test report\n\n\n    After pushing our code changes, we can review the results of our tests in\n    the GitLab UI in the Pipeline view in the `Tests` tab:\n\n\n    ![GitLab pipeline view shows test\n    results](https://res.cloudinary.com/about-gitlab-com/image/upload/v17496769\\\n    98/Blog/Content%20Images/2.0-passed-tests-UI.png)\n\n\n    ## Simulate a test failure\n\n\n    To demonstrate how our UI will handle test failures, we can intentionally\n    introduce a bug into our code and observe the resulting behavior.\\\n\n\n    Let's modify our `parseAirQualityResponse` function to introduce an error.\n    We can change the AQI category for an AQI value of 2 from \\\"Fair\\\" to\n    \\\"Poor.\\\" This change will cause the related test to fail, allowing us to\n    see the test failure in the GitLab UI.\n\n\n    In `functions.cpp`, find the `parseAirQualityResponse` function and modify\n    the switch statement for case `2` to set the `Poor` value instead of `Fair`:\n\n\n    ```cpp\n\n    \\               // Intentional bug:\n\n    \\               case 2:\n\n    \\                   aqiCategory = \\\"Poor\\\";\n\n    \\                   break;\n\n    ```\n\n\n    In tests.cpp, add a new test case that directly checks the output of the\n    `parseAirQualityResponse` function. This test ensures that the\n    `parseAirQualityResponse` function correctly parses and categorizes the air\n    quality data from the mock API response. This function takes a JSON\n    response, extracts the AQI value, and translates it into a human-readable\n    category.\n\n\n    ```cpp\n\n\n    TEST_CASE(\\\"Parse Air Quality Response\\\", \\\"[airquality]\\\") {\n\n    \\   std::string mockResponse = R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\":\n    2}}]})\\\";\n\n    \\   std::string result = parseAirQualityResponse(mockResponse);\n\n    \\   // This should fail due to the intentional bug\n\n    \\   REQUIRE(result == \\\"2 (Fair)\\\");\n\n    }\n\n\n    ```\n\n\n    Commit the changes, and push them into the MR. Open the MR in your\n    browser.\\\n\n\n    By introducing an intentional bug in this function, we can see how a test\n    failure is reported in GitLab's pipelines UI. We must add, commit, and push\n    the changes to our repository to view the test failure in the pipeline.\\\n\n\n    ![Simulated test\n    failure](https://res.cloudinary.com/about-gitlab-com/image/upload/v17496769\\\n    98/Blog/Content%20Images/2.1-failed-test-simulation.png)\n\n\n    ![Details of the simulated failed\n    test](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676998/\\\n    Blog/Content%20Images/2.2-failed-test-simulation-details.png)\n\n\n    Once we've verified this simulated test failure, we can use `git revert` to\n    roll back that commit.\\\n\n\n    ```shell\n\n    git revert\n\n    ```\n\n\n    ## Add and test a new feature\n\n\n    Let’s put what you've learned together by creating a new feature in the air\n    quality application and then writing a test for that feature using Catch2.\n    The new feature will fetch the current weather forecast for the provided zip\n    code.\n\n\n    First, we'll define a `Weather` struct and add the function prototype in our\n    `functions.h` file (inside the `#endif`):\n\n\n    ```cpp\n\n\n    struct Weather {\n\n    \\   std::string main;\n\n    \\   std::string description;\n\n    \\   double temperature;\n\n    };\n\n\n    Weather getCurrentWeather(const std::string& apiKey, double lat, double\n    lon);\n\n    ```\n\n\n    Then, we implement the `getCurrentWeather` function in `functions.cpp`. This\n    function calls the OpenWeatherMap API to retrieve the current weather and\n    parses the JSON response. This code was generated using [GitLab\n    Duo](https://about.gitlab.com/gitlab-duo-agent-platform/). If you start typing `Weather\n    getCurrentWeather(const std::string& apiKey, double lat, double lon) {` to\n    complete the function, GitLab Duo will provide the function contents for\n    you, line by line.\\\n\n\n    ![GitLab Duo completing the function\n    contents](https://res.cloudinary.com/about-gitlab-com/image/upload/v1749676\\\n    998/Blog/Content%20Images/3.get-current-weather-function-completion.png)\n\n\n    Here's what your `getCurrentWeather()` function can look like:\\\n\n\n    ```cpp\n\n\n    Weather getCurrentWeather(const std::string& apiKey, double lat, double lon)\n    {\n\n    \\   std::string url =\n    \\\"http://api.openweathermap.org/data/2.5/weather?lat=\\\" +\n    std::to_string(lat) + \\\"&lon=\\\" + std::to_string(lon) + \\\"&appid=\\\" +\n    apiKey;\n\n    \\   std::string response = httpRequest(url);\n\n    \\   auto json = nlohmann::json::parse(response);\n\n    \\   Weather weather;\n\n    \\   if (!json.is_null()) {\n\n    \\       weather.main = json[\\\"weather\\\"][0][\\\"main\\\"];\n\n    \\       weather.description = json[\\\"weather\\\"][0][\\\"description\\\"];\n\n    \\       weather.temperature = json[\\\"main\\\"][\\\"temp\\\"];\n\n    \\   }\n\n    \\   return weather;\n\n    }\n\n    ```\n\n\n    And, finally, we update our `main.cpp` file in the main function to output\n    the current forecast (and converting Kelvin to Celsius for the output): \\\n\n\n    ```cpp\n\n    \\   Weather currentWeather = getCurrentWeather(apiKey, lat, lon);\n\n    \\   if (currentWeather.main.empty()) {\n\n    \\       std::cerr \u003C\u003C \\\"Failed to fetch current weather.\\\" \u003C\u003C std::endl;\n\n    \\       return 1;\n\n    \\   }\n\n\n    \\   std::cout \u003C\u003C \\\"Current Weather: \\\" \u003C\u003C currentWeather.main \u003C\u003C \\\", \\\" \u003C\u003C\n    currentWeather.description\n\n    \\       \u003C\u003C \\\", temperature \\\" \u003C\u003C currentWeather.temperature - 273.15 \u003C\u003C \\\"\n    °C\\\" \u003C\u003C std::endl;\n\n    ```\n\n\n    We can confirm that our new feature is working by building and running the\n    application: \\\n\n\n    ```shell\n\n    cmake --build build\n\n    ./build/air_quality_app\\\n\n    ```\n\n\n    And we should see the following output or similar in case the weather is\n    different on the day the code is run :)\n\n\n    ```text\n\n    Air Quality Index for Zip Code 90210: 2 (Poor)\n\n    Current Weather: Clouds, broken clouds, temperature 23.2 °C\n\n    ```\n\n\n    With all new functionality, there should be testing! We can also write a\n    test to check whether the application is fetching and parsing a weather\n    forecast correctly. This test checks that the function returns a list\n    containing the correct number of forecast entries and that each entry has\n    accurate data regarding time and temperature.\n\n\n    ```cpp\n\n    TEST_CASE(\\\"Current Weather functionality\\\", \\\"[api]\\\") {\n\n    \\   auto weather = getCurrentWeather(\\\"dummyApiKey\\\", 40.7128, -74.0060);\n\n    \\   // Ensure main weather description is not empty\n\n    \\   REQUIRE_FALSE(weather.main.empty());\n\n    \\   // Validate that temperature is a reasonable value\n\n    \\   REQUIRE(weather.temperature > 0);\\\n\n    }\n\n    ```\n\n\n    We’ll also have to update our `mockHTTPRequest` function in `tests.cpp` to\n    account for this new test. Modify the if-condition with a new else-if branch\n    checking for the `weather` string in the URL: \\\n\n\n    ```cpp\n\n    // Mock HTTP request function that simulates API responses\n\n    std::string mockHttpRequest(const std::string &url)\n\n    {\n\n    \\   if (url.find(\\\"geo\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for geocoding\n\n    \\       return R\\\"({\\\"lat\\\": 40.7128, \\\"lon\\\": -74.0060})\\\";\n\n    \\   }\n\n    \\   else if (url.find(\\\"air_pollution\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for air quality\n\n    \\       return R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\": 2}}]})\\\";\n\n    \\   }\n\n    \\   else if (url.find(\\\"weather\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for current weather\n\n    \\       return R\\\"({\n\n    \\          \\\"weather\\\": [{\\\"main\\\": \\\"Clear\\\", \\\"description\\\": \\\"clear\n    sky\\\"}],\n\n    \\          \\\"main\\\": {\\\"temp\\\": 298.55}\n\n    \\      })\\\";\n\n    \\   }\n\n    \\   return \\\"{}\\\";\n\n    }\n\n    ```\n\n\n    And verify that our tests are working by rebuilding and running our tests:\n    \\\n\n\n    ```shell\n\n    cmake --build build\\\n\n    ./build/tests\n\n    ```\n\n\n    All tests should pass, including the new one for Current Weather\n    Functionality.\\\n\n\n    ## Optimize tests.cpp with sections\n\n\n    To better organize our tests as the project grows and categorize each\n    functionality, we can use Catch2’s `SECTION` macro. The `SECTION` macro\n    allows you to define logically separate test scenarios within a single test\n    case, providing a clean way to test different behaviors or conditions\n    without requiring multiple separate test cases or multiple files. This\n    approach keeps related tests bundled together and also improves test\n    maintainability by allowing shared setup code to be executed repeatedly for\n    each section.\n\n\n    Since some of our functionality is preprocessing data to retrieve\n    information, let’s section our tests as such:\n\n    - preprocessing steps:\\\n\n    \\t- API key validation\n\n    \\t- geocoding validation\n\n    -  API data retrieval:\n\n    \\t- air pollution retrieval\\\n\n    \\t- forecast retrieval\n\n\n    Here’s what our `tests.cpp` will look like if organized by sections:\\\n\n\n    ```cpp\n\n    #include \\\"functions.h\\\"\n\n    #include \u003Ccatch2/catch_test_macros.hpp>\n\n    #include \u003Cstring>\n\n\n    // Mock HTTP request function that simulates API responses\n\n    std::string mockHttpRequest(const std::string &url)\n\n    {\n\n    \\   if (url.find(\\\"geo\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for geocoding\n\n    \\       return R\\\"({\\\"lat\\\": 40.7128, \\\"lon\\\": -74.0060})\\\";\n\n    \\   }\n\n    \\   else if (url.find(\\\"air_pollution\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for air quality\n\n    \\       return R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\": 2}}]})\\\";\n\n    \\   }\n\n    \\   else if (url.find(\\\"weather\\\") != std::string::npos)\n\n    \\   {\n\n    \\       // Mock response for current weather\n\n    \\       return R\\\"({\n\n    \\          \\\"weather\\\": [{\\\"main\\\": \\\"Clear\\\", \\\"description\\\": \\\"clear\n    sky\\\"}],\n\n    \\          \\\"main\\\": {\\\"temp\\\": 298.55}\n\n    \\      })\\\";\n\n    \\   }\n\n    \\   return \\\"{}\\\";\n\n    }\n\n\n    // Overriding the actual httpRequest function with the mockHttpRequest for\n    testing\n\n    std::string httpRequest(const std::string &url)\n\n    {\n\n    \\   return mockHttpRequest(url);\n\n    }\n\n\n    // Preprocessing Steps\n\n    TEST_CASE(\\\"Preprocessing Steps\\\", \\\"[preprocessing]\\\") {\n\n    \\   SECTION(\\\"API Key Retrieval\\\") {\n\n    \\       // Set the API_KEY environment variable for testing\n\n    \\       setenv(\\\"API_KEY\\\", \\\"test_key\\\", 1);\n\n    \\       // Test if the key is retrieved correctly\n\n    \\       REQUIRE_FALSE(getApiKey().empty());\n\n    \\   }\n\n\n    \\   SECTION(\\\"Geocode Functionality\\\") {\n\n    \\       std::string apiKey = \\\"test_key\\\";\n\n    \\       std::pair\u003Cdouble, double> coordinates = geocodeZipcode(\\\"90210\\\",\n    apiKey);\n\n    \\       // Check latitude\n\n    \\       REQUIRE(coordinates.first == 40.7128);\n\n    \\       // Check longitude\\\n\n    \\       REQUIRE(coordinates.second == -74.0060);\n\n    \\   }\n\n    }\n\n\n    // API Data Retrieval\n\n    TEST_CASE(\\\"API Data Retrieval\\\", \\\"[data_retrieval]\\\") {\n\n    \\   SECTION(\\\"Air Quality Functionality\\\") {\n\n    \\       std::string apiKey = \\\"test_key\\\";\n\n    \\       double lat = 40.7128;\n\n    \\       double lon = -74.0060;\n\n    \\       std::string response = fetchAirQuality(lat, lon, apiKey);\n\n    \\       // Check the response\n\n    \\       REQUIRE(response == R\\\"({\\\"list\\\": [{\\\"main\\\": {\\\"aqi\\\": 2}}]})\\\");\n\n    \\   }\n\n\n    \\   SECTION(\\\"Current Weather Functionality\\\") {\n\n    \\       auto weather = getCurrentWeather(\\\"dummyApiKey\\\", 40.7128,\n    -74.0060);\n\n    \\       // Ensure main weather description is not empty\n\n    \\       REQUIRE_FALSE(weather.main.empty());\n\n    \\       // Validate that temperature is a reasonable value\n\n    \\       REQUIRE(weather.temperature > 0);\n\n    \\   }\n\n    }\n\n    ```\n\n\n    Rebuild the code and run the tests again to verify.\n\n\n    ```shell\n\n    cmake --build build\\\n\n    ./build/tests\n\n    ```\n\n\n    ## Next steps\n\n\n    In this post, we covered how to integrate unit testing into a `C++` project\n    using Catch2 testing framework and GitLab CI/CD and set up basic tests for\n    our reference air quality application project.\n\n\n    To explore these concepts further, you can check out the [Catch2\n    documentation](https://github.com/catchorg/Catch2) and [GitLab's Unit test\n    report examples\n    documentation](https://docs.gitlab.com/ci/testing/unit_test_report_examp/\n    les.html).\\\n\n\n    For an advanced async exercise, you could build upon this project by using\n    GitLab Duo to implement a feature that retrieves and analyzes historical air\n    quality data and add code quality checks into the CI/CD pipeline. Happy\n    coding!\\ \\n\"\n  category: devsecops\n  tags:\n    - tutorial\n    - testing\n    - CI\n    - AI/ML\n    - DevSecOps\nconfig:\n  slug: develop-c-unit-testing-with-catch2-junit-and-gitlab-ci\n  featured: true\n  template: BlogPost\n",{"title":5,"description":17,"ogTitle":5,"ogDescription":17,"noIndex":33,"ogImage":19,"ogUrl":34,"ogSiteName":35,"ogType":36,"canonicalUrls":34},false,"https://about.gitlab.com/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci","https://about.gitlab.com","article","en-us/blog/develop-c-unit-testing-with-catch2-junit-and-gitlab-ci",[22,23,39,40,11],"ci","aiml",[22,23,24,25,26],"rhQcJBYPfM3_ItZtmQ0bgoK0IiBPyvQ9eG_r9qksiy0",{"data":44},{"logo":45,"freeTrial":50,"sales":55,"login":60,"items":65,"search":374,"minimal":405,"duo":424,"switchNav":433,"pricingDeployment":444},{"config":46},{"href":47,"dataGaName":48,"dataGaLocation":49},"/","gitlab logo","header",{"text":51,"config":52},"Get free trial",{"href":53,"dataGaName":54,"dataGaLocation":49},"https://gitlab.com/-/trial_registrations/new?glm_source=about.gitlab.com&glm_content=default-saas-trial/","free trial",{"text":56,"config":57},"Talk to sales",{"href":58,"dataGaName":59,"dataGaLocation":49},"/sales/","sales",{"text":61,"config":62},"Sign in",{"href":63,"dataGaName":64,"dataGaLocation":49},"https://gitlab.com/users/sign_in/","sign in",[66,93,188,193,295,355],{"text":67,"config":68,"cards":70},"Platform",{"dataNavLevelOne":69},"platform",[71,77,85],{"title":67,"description":72,"link":73},"The intelligent orchestration platform for DevSecOps",{"text":74,"config":75},"Explore our Platform",{"href":76,"dataGaName":69,"dataGaLocation":49},"/platform/",{"title":78,"description":79,"link":80},"GitLab Duo Agent Platform","Agentic AI for the entire software lifecycle",{"text":81,"config":82},"Meet GitLab Duo",{"href":83,"dataGaName":84,"dataGaLocation":49},"/gitlab-duo-agent-platform/","gitlab duo agent platform",{"title":86,"description":87,"link":88},"Why GitLab","See the top reasons enterprises choose GitLab",{"text":89,"config":90},"Learn more",{"href":91,"dataGaName":92,"dataGaLocation":49},"/why-gitlab/","why gitlab",{"text":94,"left":14,"config":95,"link":97,"lists":101,"footer":170},"Product",{"dataNavLevelOne":96},"solutions",{"text":98,"config":99},"View all Solutions",{"href":100,"dataGaName":96,"dataGaLocation":49},"/solutions/",[102,126,149],{"title":103,"description":104,"link":105,"items":110},"Automation","CI/CD and automation to accelerate deployment",{"config":106},{"icon":107,"href":108,"dataGaName":109,"dataGaLocation":49},"AutomatedCodeAlt","/solutions/delivery-automation/","automated software delivery",[111,115,118,122],{"text":112,"config":113},"CI/CD",{"href":114,"dataGaLocation":49,"dataGaName":112},"/solutions/continuous-integration/",{"text":78,"config":116},{"href":83,"dataGaLocation":49,"dataGaName":117},"gitlab duo agent platform - product menu",{"text":119,"config":120},"Source Code Management",{"href":121,"dataGaLocation":49,"dataGaName":119},"/solutions/source-code-management/",{"text":123,"config":124},"Automated Software Delivery",{"href":108,"dataGaLocation":49,"dataGaName":125},"Automated software delivery",{"title":127,"description":128,"link":129,"items":134},"Security","Deliver code faster without compromising security",{"config":130},{"href":131,"dataGaName":132,"dataGaLocation":49,"icon":133},"/solutions/application-security-testing/","security and compliance","ShieldCheckLight",[135,139,144],{"text":136,"config":137},"Application Security Testing",{"href":131,"dataGaName":138,"dataGaLocation":49},"Application security testing",{"text":140,"config":141},"Software Supply Chain Security",{"href":142,"dataGaLocation":49,"dataGaName":143},"/solutions/supply-chain/","Software supply chain security",{"text":145,"config":146},"Software Compliance",{"href":147,"dataGaName":148,"dataGaLocation":49},"/solutions/software-compliance/","software compliance",{"title":150,"link":151,"items":156},"Measurement",{"config":152},{"icon":153,"href":154,"dataGaName":155,"dataGaLocation":49},"DigitalTransformation","/solutions/visibility-measurement/","visibility and measurement",[157,161,165],{"text":158,"config":159},"Visibility & Measurement",{"href":154,"dataGaLocation":49,"dataGaName":160},"Visibility and Measurement",{"text":162,"config":163},"Value Stream Management",{"href":164,"dataGaLocation":49,"dataGaName":162},"/solutions/value-stream-management/",{"text":166,"config":167},"Analytics & Insights",{"href":168,"dataGaLocation":49,"dataGaName":169},"/solutions/analytics-and-insights/","Analytics and insights",{"title":171,"items":172},"GitLab for",[173,178,183],{"text":174,"config":175},"Enterprise",{"href":176,"dataGaLocation":49,"dataGaName":177},"/enterprise/","enterprise",{"text":179,"config":180},"Small Business",{"href":181,"dataGaLocation":49,"dataGaName":182},"/small-business/","small business",{"text":184,"config":185},"Public Sector",{"href":186,"dataGaLocation":49,"dataGaName":187},"/solutions/public-sector/","public sector",{"text":189,"config":190},"Pricing",{"href":191,"dataGaName":192,"dataGaLocation":49,"dataNavLevelOne":192},"/pricing/","pricing",{"text":194,"config":195,"link":197,"lists":201,"feature":286},"Resources",{"dataNavLevelOne":196},"resources",{"text":198,"config":199},"View all resources",{"href":200,"dataGaName":196,"dataGaLocation":49},"/resources/",[202,235,258],{"title":203,"items":204},"Getting started",[205,210,215,220,225,230],{"text":206,"config":207},"Install",{"href":208,"dataGaName":209,"dataGaLocation":49},"/install/","install",{"text":211,"config":212},"Quick start guides",{"href":213,"dataGaName":214,"dataGaLocation":49},"/get-started/","quick setup checklists",{"text":216,"config":217},"Learn",{"href":218,"dataGaLocation":49,"dataGaName":219},"https://university.gitlab.com/","learn",{"text":221,"config":222},"Product documentation",{"href":223,"dataGaName":224,"dataGaLocation":49},"https://docs.gitlab.com/","product documentation",{"text":226,"config":227},"Best practice videos",{"href":228,"dataGaName":229,"dataGaLocation":49},"/getting-started-videos/","best practice videos",{"text":231,"config":232},"Integrations",{"href":233,"dataGaName":234,"dataGaLocation":49},"/integrations/","integrations",{"title":236,"items":237},"Discover",[238,243,248,253],{"text":239,"config":240},"Customer success stories",{"href":241,"dataGaName":242,"dataGaLocation":49},"/customers/","customer success stories",{"text":244,"config":245},"Blog",{"href":246,"dataGaName":247,"dataGaLocation":49},"/blog/","blog",{"text":249,"config":250},"The Source",{"href":251,"dataGaName":252,"dataGaLocation":49},"/the-source/","the source",{"text":254,"config":255},"Remote",{"href":256,"dataGaName":257,"dataGaLocation":49},"https://handbook.gitlab.com/handbook/company/culture/all-remote/","remote",{"title":259,"items":260},"Connect",[261,266,271,276,281],{"text":262,"config":263},"GitLab Services",{"href":264,"dataGaName":265,"dataGaLocation":49},"/services/","services",{"text":267,"config":268},"Community",{"href":269,"dataGaName":270,"dataGaLocation":49},"/community/","community",{"text":272,"config":273},"Forum",{"href":274,"dataGaName":275,"dataGaLocation":49},"https://forum.gitlab.com/","forum",{"text":277,"config":278},"Events",{"href":279,"dataGaName":280,"dataGaLocation":49},"/events/","events",{"text":282,"config":283},"Partners",{"href":284,"dataGaName":285,"dataGaLocation":49},"/partners/","partners",{"textColor":287,"title":288,"text":289,"link":290},"#000","What’s new in GitLab","Stay updated with our latest features and improvements.",{"text":291,"config":292},"Read the latest",{"href":293,"dataGaName":294,"dataGaLocation":49},"/releases/whats-new/","whats new",{"text":296,"config":297,"lists":299},"Company",{"dataNavLevelOne":298},"company",[300],{"items":301},[302,307,313,315,320,325,330,335,340,345,350],{"text":303,"config":304},"About",{"href":305,"dataGaName":306,"dataGaLocation":49},"/company/","about",{"text":308,"config":309,"footerGa":312},"Jobs",{"href":310,"dataGaName":311,"dataGaLocation":49},"/jobs/","jobs",{"dataGaName":311},{"text":277,"config":314},{"href":279,"dataGaName":280,"dataGaLocation":49},{"text":316,"config":317},"Leadership",{"href":318,"dataGaName":319,"dataGaLocation":49},"/company/team/e-group/","leadership",{"text":321,"config":322},"Team",{"href":323,"dataGaName":324,"dataGaLocation":49},"/company/team/","team",{"text":326,"config":327},"Handbook",{"href":328,"dataGaName":329,"dataGaLocation":49},"https://handbook.gitlab.com/","handbook",{"text":331,"config":332},"Investor relations",{"href":333,"dataGaName":334,"dataGaLocation":49},"https://ir.gitlab.com/","investor relations",{"text":336,"config":337},"Trust Center",{"href":338,"dataGaName":339,"dataGaLocation":49},"/security/","trust center",{"text":341,"config":342},"AI Transparency Center",{"href":343,"dataGaName":344,"dataGaLocation":49},"/ai-transparency-center/","ai transparency center",{"text":346,"config":347},"Newsletter",{"href":348,"dataGaName":349,"dataGaLocation":49},"/company/contact/#contact-forms","newsletter",{"text":351,"config":352},"Press",{"href":353,"dataGaName":354,"dataGaLocation":49},"/press/","press",{"text":356,"config":357,"lists":358},"Contact us",{"dataNavLevelOne":298},[359],{"items":360},[361,364,369],{"text":56,"config":362},{"href":58,"dataGaName":363,"dataGaLocation":49},"talk to sales",{"text":365,"config":366},"Support portal",{"href":367,"dataGaName":368,"dataGaLocation":49},"https://support.gitlab.com","support portal",{"text":370,"config":371},"Customer portal",{"href":372,"dataGaName":373,"dataGaLocation":49},"https://customers.gitlab.com/customers/sign_in/","customer portal",{"close":375,"login":376,"suggestions":383},"Close",{"text":377,"link":378},"To search repositories and projects, login to",{"text":379,"config":380},"gitlab.com",{"href":63,"dataGaName":381,"dataGaLocation":382},"search login","search",{"text":384,"default":385},"Suggestions",[386,388,392,394,398,402],{"text":78,"config":387},{"href":83,"dataGaName":78,"dataGaLocation":382},{"text":389,"config":390},"Code Suggestions (AI)",{"href":391,"dataGaName":389,"dataGaLocation":382},"/solutions/code-suggestions/",{"text":112,"config":393},{"href":114,"dataGaName":112,"dataGaLocation":382},{"text":395,"config":396},"GitLab on AWS",{"href":397,"dataGaName":395,"dataGaLocation":382},"/partners/technology-partners/aws/",{"text":399,"config":400},"GitLab on Google Cloud",{"href":401,"dataGaName":399,"dataGaLocation":382},"/partners/technology-partners/google-cloud-platform/",{"text":403,"config":404},"Why GitLab?",{"href":91,"dataGaName":403,"dataGaLocation":382},{"freeTrial":406,"mobileIcon":411,"desktopIcon":416,"secondaryButton":419},{"text":407,"config":408},"Start free trial",{"href":409,"dataGaName":54,"dataGaLocation":410},"https://gitlab.com/-/trials/new/","nav",{"altText":412,"config":413},"Gitlab Icon",{"src":414,"dataGaName":415,"dataGaLocation":410},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1758203874/jypbw1jx72aexsoohd7x.svg","gitlab icon",{"altText":412,"config":417},{"src":418,"dataGaName":415,"dataGaLocation":410},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1758203875/gs4c8p8opsgvflgkswz9.svg",{"text":420,"config":421},"Get Started",{"href":422,"dataGaName":423,"dataGaLocation":410},"https://gitlab.com/-/trial_registrations/new?glm_source=about.gitlab.com/get-started/","get started",{"freeTrial":425,"mobileIcon":429,"desktopIcon":431},{"text":426,"config":427},"Learn more about GitLab Duo",{"href":83,"dataGaName":428,"dataGaLocation":410},"gitlab duo",{"altText":412,"config":430},{"src":414,"dataGaName":415,"dataGaLocation":410},{"altText":412,"config":432},{"src":418,"dataGaName":415,"dataGaLocation":410},{"button":434,"mobileIcon":439,"desktopIcon":441},{"text":435,"config":436},"/switch",{"href":437,"dataGaName":438,"dataGaLocation":410},"#contact","switch",{"altText":412,"config":440},{"src":414,"dataGaName":415,"dataGaLocation":410},{"altText":412,"config":442},{"src":443,"dataGaName":415,"dataGaLocation":410},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1773335277/ohhpiuoxoldryzrnhfrh.png",{"freeTrial":445,"mobileIcon":450,"desktopIcon":452},{"text":446,"config":447},"Back to pricing",{"href":191,"dataGaName":448,"dataGaLocation":410,"icon":449},"back to pricing","GoBack",{"altText":412,"config":451},{"src":414,"dataGaName":415,"dataGaLocation":410},{"altText":412,"config":453},{"src":418,"dataGaName":415,"dataGaLocation":410},{"title":455,"button":456,"config":461},"See how agentic AI transforms software delivery",{"text":457,"config":458},"Watch GitLab Transcend now",{"href":459,"dataGaName":460,"dataGaLocation":49},"/events/transcend/virtual/","transcend event",{"layout":462,"icon":463,"disabled":14},"release","AiStar",{"data":465},{"text":466,"source":467,"edit":473,"contribute":478,"config":483,"items":488,"minimal":693},"Git is a trademark of Software Freedom Conservancy and our use of 'GitLab' is under license",{"text":468,"config":469},"View page source",{"href":470,"dataGaName":471,"dataGaLocation":472},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/","page source","footer",{"text":474,"config":475},"Edit this page",{"href":476,"dataGaName":477,"dataGaLocation":472},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/-/blob/main/content/","web ide",{"text":479,"config":480},"Please contribute",{"href":481,"dataGaName":482,"dataGaLocation":472},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/-/blob/main/CONTRIBUTING.md/","please contribute",{"twitter":484,"facebook":485,"youtube":486,"linkedin":487},"https://twitter.com/gitlab","https://www.facebook.com/gitlab","https://www.youtube.com/channel/UCnMGQ8QHMAnVIsI3xJrihhg","https://www.linkedin.com/company/gitlab-com",[489,536,588,632,659],{"title":189,"links":490,"subMenu":505},[491,495,500],{"text":492,"config":493},"View plans",{"href":191,"dataGaName":494,"dataGaLocation":472},"view plans",{"text":496,"config":497},"Why Premium?",{"href":498,"dataGaName":499,"dataGaLocation":472},"/pricing/premium/","why premium",{"text":501,"config":502},"Why Ultimate?",{"href":503,"dataGaName":504,"dataGaLocation":472},"/pricing/ultimate/","why ultimate",[506],{"title":507,"links":508},"Contact Us",[509,512,514,516,521,526,531],{"text":510,"config":511},"Contact sales",{"href":58,"dataGaName":59,"dataGaLocation":472},{"text":365,"config":513},{"href":367,"dataGaName":368,"dataGaLocation":472},{"text":370,"config":515},{"href":372,"dataGaName":373,"dataGaLocation":472},{"text":517,"config":518},"Status",{"href":519,"dataGaName":520,"dataGaLocation":472},"https://status.gitlab.com/","status",{"text":522,"config":523},"Terms of use",{"href":524,"dataGaName":525,"dataGaLocation":472},"/terms/","terms of use",{"text":527,"config":528},"Privacy statement",{"href":529,"dataGaName":530,"dataGaLocation":472},"/privacy/","privacy statement",{"text":532,"config":533},"Cookie preferences",{"dataGaName":534,"dataGaLocation":472,"id":535,"isOneTrustButton":14},"cookie preferences","ot-sdk-btn",{"title":94,"links":537,"subMenu":546},[538,542],{"text":539,"config":540},"DevSecOps platform",{"href":76,"dataGaName":541,"dataGaLocation":472},"devsecops platform",{"text":543,"config":544},"AI-Assisted Development",{"href":83,"dataGaName":545,"dataGaLocation":472},"ai-assisted development",[547],{"title":548,"links":549},"Topics",[550,555,560,565,570,573,578,583],{"text":551,"config":552},"CICD",{"href":553,"dataGaName":554,"dataGaLocation":472},"/topics/ci-cd/","cicd",{"text":556,"config":557},"GitOps",{"href":558,"dataGaName":559,"dataGaLocation":472},"/topics/gitops/","gitops",{"text":561,"config":562},"DevOps",{"href":563,"dataGaName":564,"dataGaLocation":472},"/topics/devops/","devops",{"text":566,"config":567},"Version Control",{"href":568,"dataGaName":569,"dataGaLocation":472},"/topics/version-control/","version control",{"text":26,"config":571},{"href":572,"dataGaName":11,"dataGaLocation":472},"/topics/devsecops/",{"text":574,"config":575},"Cloud Native",{"href":576,"dataGaName":577,"dataGaLocation":472},"/topics/cloud-native/","cloud native",{"text":579,"config":580},"AI for Coding",{"href":581,"dataGaName":582,"dataGaLocation":472},"/topics/devops/ai-for-coding/","ai for coding",{"text":584,"config":585},"Agentic AI",{"href":586,"dataGaName":587,"dataGaLocation":472},"/topics/agentic-ai/","agentic ai",{"title":589,"links":590},"Solutions",[591,593,595,600,604,607,611,614,616,619,622,627],{"text":136,"config":592},{"href":131,"dataGaName":136,"dataGaLocation":472},{"text":125,"config":594},{"href":108,"dataGaName":109,"dataGaLocation":472},{"text":596,"config":597},"Agile development",{"href":598,"dataGaName":599,"dataGaLocation":472},"/solutions/agile-delivery/","agile delivery",{"text":601,"config":602},"SCM",{"href":121,"dataGaName":603,"dataGaLocation":472},"source code management",{"text":551,"config":605},{"href":114,"dataGaName":606,"dataGaLocation":472},"continuous integration & delivery",{"text":608,"config":609},"Value stream management",{"href":164,"dataGaName":610,"dataGaLocation":472},"value stream management",{"text":556,"config":612},{"href":613,"dataGaName":559,"dataGaLocation":472},"/solutions/gitops/",{"text":174,"config":615},{"href":176,"dataGaName":177,"dataGaLocation":472},{"text":617,"config":618},"Small business",{"href":181,"dataGaName":182,"dataGaLocation":472},{"text":620,"config":621},"Public sector",{"href":186,"dataGaName":187,"dataGaLocation":472},{"text":623,"config":624},"Education",{"href":625,"dataGaName":626,"dataGaLocation":472},"/solutions/education/","education",{"text":628,"config":629},"Financial services",{"href":630,"dataGaName":631,"dataGaLocation":472},"/solutions/finance/","financial services",{"title":194,"links":633},[634,636,638,640,643,645,647,649,651,653,655,657],{"text":206,"config":635},{"href":208,"dataGaName":209,"dataGaLocation":472},{"text":211,"config":637},{"href":213,"dataGaName":214,"dataGaLocation":472},{"text":216,"config":639},{"href":218,"dataGaName":219,"dataGaLocation":472},{"text":221,"config":641},{"href":223,"dataGaName":642,"dataGaLocation":472},"docs",{"text":244,"config":644},{"href":246,"dataGaName":247,"dataGaLocation":472},{"text":239,"config":646},{"href":241,"dataGaName":242,"dataGaLocation":472},{"text":254,"config":648},{"href":256,"dataGaName":257,"dataGaLocation":472},{"text":262,"config":650},{"href":264,"dataGaName":265,"dataGaLocation":472},{"text":267,"config":652},{"href":269,"dataGaName":270,"dataGaLocation":472},{"text":272,"config":654},{"href":274,"dataGaName":275,"dataGaLocation":472},{"text":277,"config":656},{"href":279,"dataGaName":280,"dataGaLocation":472},{"text":282,"config":658},{"href":284,"dataGaName":285,"dataGaLocation":472},{"title":296,"links":660},[661,663,665,667,669,671,673,677,682,684,686,688],{"text":303,"config":662},{"href":305,"dataGaName":298,"dataGaLocation":472},{"text":308,"config":664},{"href":310,"dataGaName":311,"dataGaLocation":472},{"text":316,"config":666},{"href":318,"dataGaName":319,"dataGaLocation":472},{"text":321,"config":668},{"href":323,"dataGaName":324,"dataGaLocation":472},{"text":326,"config":670},{"href":328,"dataGaName":329,"dataGaLocation":472},{"text":331,"config":672},{"href":333,"dataGaName":334,"dataGaLocation":472},{"text":674,"config":675},"Sustainability",{"href":676,"dataGaName":674,"dataGaLocation":472},"/sustainability/",{"text":678,"config":679},"Diversity, inclusion and belonging (DIB)",{"href":680,"dataGaName":681,"dataGaLocation":472},"/diversity-inclusion-belonging/","Diversity, inclusion and belonging",{"text":336,"config":683},{"href":338,"dataGaName":339,"dataGaLocation":472},{"text":346,"config":685},{"href":348,"dataGaName":349,"dataGaLocation":472},{"text":351,"config":687},{"href":353,"dataGaName":354,"dataGaLocation":472},{"text":689,"config":690},"Modern Slavery Transparency Statement",{"href":691,"dataGaName":692,"dataGaLocation":472},"https://handbook.gitlab.com/handbook/legal/modern-slavery-act-transparency-statement/","modern slavery transparency statement",{"items":694},[695,698,701],{"text":696,"config":697},"Terms",{"href":524,"dataGaName":525,"dataGaLocation":472},{"text":699,"config":700},"Cookies",{"dataGaName":534,"dataGaLocation":472,"id":535,"isOneTrustButton":14},{"text":702,"config":703},"Privacy",{"href":529,"dataGaName":530,"dataGaLocation":472},[705],{"id":706,"title":9,"body":28,"config":707,"content":709,"description":28,"extension":27,"meta":713,"navigation":14,"path":714,"seo":715,"stem":716,"__hash__":717},"blogAuthors/en-us/blog/authors/fatima-sarah-khalid.yml",{"template":708},"BlogAuthor",{"name":9,"config":710},{"headshot":711,"ctfId":712},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1749663337/Blog/Author%20Headshots/sugaroverflow-headshot.jpg","sugaroverflow",{},"/en-us/blog/authors/fatima-sarah-khalid",{},"en-us/blog/authors/fatima-sarah-khalid","GpfAGDKB-pWdwSjPp8CXd-29am9proj8tK7mm1IN_rs",[719,732,746],{"content":720,"config":730},{"title":721,"description":722,"authors":723,"heroImage":725,"date":726,"body":727,"category":11,"tags":728},"Teaching software development the easy way using GitLab","Learn how University of Washington lecturer Stephen G. Dame uses GitLab for Education to manage student assignments, distribute course materials, and provide inline code feedback at scale.\n",[724],"Rod Burns","https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659537/Blog/Hero%20Images/display-article-image-0679-1800x945-fy26.png","2026-04-29","For instructors teaching software development, one of the biggest logistical challenges is assignment distribution and feedback at scale. How do you give large groups of students access to course materials, keep solution code private, and still deliver meaningful, contextual feedback without lots of administrative overhead?\n\nThe **[GitLab for Education program](https://about.gitlab.com/solutions/education/)** provides qualifying institutions with free access to **GitLab Ultimate**, enabling instructors to build professional-grade workflows that mirror real-world software development environments. In this article, you'll learn how Stephen G. Dame, a lecturer in the Computing and Software Systems department at the University of Washington, Bothell, uses simple workflows in GitLab to manage everything from course materials to student feedback across multiple classes.\n\n## From aerospace to academia: Bringing GitLab to the classroom\n\nDame came to academia with years of experience as a chief software engineer at Boeing Commercial Airplanes, where GitLab was used for aerospace projects. As an adjunct professor, he became an early advocate for GitLab within the university, joining the GitLab for Education program to access the full feature set needed to run structured, scalable course workflows.\n\n> **\"GitLab provides the greatest way to organize multiple classes, student assignments, lectures, and code samples through the use of Groups and Subgroups, which I found to be unique to GitLab compared to other repository platforms.\"**\n>\n> - Stephen G. Dame, University of Washington, Bothell\n\n## Set up groups: Build the right structure before writing a line of code\n\nThe foundation of an effective GitLab-based course is a well-planned group hierarchy. GitLab's **[Groups and Subgroups](https://docs.gitlab.com/tutorials/manage_user/#create-the-organization-parent-group-and-subgroups)** allow instructors to model the natural structure of a university department institution, course, and role with precise, inheritable permissions at every level.\n\nDame's structure places the university at the root (`UWTeaching`), with each course occupying its own subgroup (e.g. `css430`). Within each course sit repositories for `lecture-materials` and `code`, alongside dedicated Subgroups for `students` and `graders`. Instructor materials remain private, while student and grader subgroups are configured with controlled permissions so that assignment briefs and solutions are visible only to the right people.\n\n![Screenshot of GitLab group hierarchy — institution, course subgroup, and per-student subgroups](https://res.cloudinary.com/about-gitlab-com/image/upload/v1777463673/dpxfnitv76pdmvcqtgag.png)\n\nPermissions cascade downward through the hierarchy via **Manage > Members**, allowing Dame to add students to a course's `students` subgroup with `Reporter` access and an expiration date tied to the end of the academic quarter. Students can clone and pull from assignment repositories but cannot push — keeping solution code firmly under instructor control.\n\nStudents are guided to set up SSH keys across all their working environments (local machines, cloud shells, virtual machines) so they can clone repositories and receive weekly updates via `git pull`. They copy relevant code into their own private repositories to manage their own version history.\n\n**Tip for large classes:** For larger cohorts, adding students by hand is impractical. GitLab's REST API lets you automate subgroup creation and membership from a list of usernames. Below is a sample Python script that handles this:\n\n```python\n    import gitlab\n    from datetime import datetime\n\n    # Connect to your GitLab instance\n    gl = gitlab.Gitlab('https://gitlab.com', private_token='YOUR_PRIVATE_TOKEN')\n\n    # Target parent group ID (e.g., the ID for \"css430 > students\")\n    parent_group_id = 12345678\n\n    # Set expiration: typically the beginning of the next month after quarter end\n    expiry_date = '2025-01-01'\n\n    # List of collected student usernames\n    student_list = ['alice_css430', 'bob_css430', 'carol_css430', 'dave_css430', 'eve_css430']\n\n    for username in student_list:\n        try:\n            # 1. Create a personal subgroup for the student\n            subgroup = gl.groups.create({\n                'name': username,\n                'path': username,\n                'parent_id': parent_group_id,\n                'visibility': 'private'\n            })\n\n            # 2. Add student to the new subgroup with Expiration\n            user = gl.users.list(username=username)[0]\n            subgroup.members.create({\n                'user_id': user.id,\n                'access_level': gitlab.const.REPORTER_ACCESS,\n                'expires_at': expiry_date\n            })\n            print(f\"Success: Subgroup created and student added for {username}\")\n        except Exception as e:\n            print(f\"Error processing {username}: {e}\")\n```\nThere is also an [open source project that automates class management](https://gitlab.com/edu-docs/class-management-automation) published by GitLab that provides additional tooling for this workflow.\n## Give feedback where the work actually lives\n\nOnce the structure is in place, the feedback workflow is where GitLab's value becomes most apparent to students. Dame asks students to submit assignments by opening a **[merge request](https://docs.gitlab.com/user/project/merge_requests/)** in their repository. This gives instructors an immediate, clean diff of everything the student has written.\n![A GitLab merge request showing inline code comment function for an instructor](https://res.cloudinary.com/about-gitlab-com/image/upload/v1777467468/icclzyglbkwlvfysggbi.png)\nInstructors can click any line of code and leave an **inline comment** — not just flagging what is wrong, but explaining why, and pointing to what to look at next. Students receive this feedback in direct context with their code, which is far more actionable than a comment at the bottom of a submitted document.\n\n## Join GitLab for Education\n\nSetting up your first GitLab assignment takes some initial effort, but once the structure is in place it largely runs itself. The real payoff goes beyond organization: Students graduate having worked daily in an environment that mirrors professional software development, building habits around [version control](https://about.gitlab.com/topics/version-control/) and [code review](https://docs.gitlab.com/development/code_review/) rather than learning them as abstract concepts.\n\nIf you are just getting started, keep it simple. Begin with a single course group, one assignment template, and a basic pipeline. The structure will grow naturally alongside your confidence with the platform.\n\nMake sure to **[sign up for GitLab for Education](https://about.gitlab.com/solutions/education/join/)** so that you and your students can access all top-tier features, including unlimited reviewers on merge requests, additional compute minutes, and expanded storage.\n\n> [Apply to the GitLab for Education program today](https://about.gitlab.com/solutions/education/join/).",[626,729],"open source",{"featured":33,"template":15,"slug":731},"teaching-software-development-the-easy-way-using-gitlab",{"content":733,"config":744},{"description":734,"authors":735,"heroImage":737,"date":738,"title":739,"body":740,"category":11,"tags":741},"AI-generated code is 34% of development work. Discover how to balance productivity gains with quality, reliability, and security.",[736],"Manav Khurana","https://res.cloudinary.com/about-gitlab-com/image/upload/v1767982271/e9ogyosmuummq7j65zqg.png","2026-01-08","AI is reshaping DevSecOps: Attend GitLab Transcend to see what’s next","AI promises a step change in innovation velocity, but most software teams are hitting a wall. According to our latest [Global DevSecOps Report](https://about.gitlab.com/developer-survey/), AI-generated code now accounts for 34% of all development work. Yet 70% of DevSecOps professionals report that AI is making compliance management more difficult, and 76% say agentic AI will create unprecedented security challenges.\n\nThis is the AI paradox: AI accelerates coding, but software delivery slows down as teams struggle to test, secure, and deploy all that code.\n\n## Productivity gains meet workflow bottlenecks\nThe problem isn't AI itself. It's how software gets built today. The traditional DevSecOps lifecycle contains hundreds of small tasks that developers must navigate manually: updating tickets, running tests, requesting reviews, waiting for approvals, fixing merge conflicts, addressing security findings. These tasks drain an average of seven hours per week from every team member, according to our research.\n\nDevelopment teams are producing code faster than ever, but that code still crawls through fragmented toolchains, manual handoffs, and disconnected processes. In fact, 60% of DevSecOps teams use more than five tools for software development overall, and 49% use more than five AI tools. This fragmentation creates collaboration barriers, with 94% of DevSecOps professionals experiencing factors that limit collaboration in the software development lifecycle.\n\nThe answer isn't more tools. It's intelligent orchestration that brings software teams and their AI agents together across projects and release cycles, with enterprise-grade security, governance, and compliance built in.\n\n## Seeking deeper human-AI partnerships\nDevSecOps professionals don't want AI to take over — they want reliable partnerships. The vast majority (82%) say using agentic AI would increase their job satisfaction, and 43% envision an ideal future with a 50/50 split between human and AI contributions. They're ready to trust AI with 37% of their daily tasks without human review, particularly for documentation, test writing, and code reviews.\n\nWhat we heard resoundingly from DevSecOps professionals is that AI won't replace them; rather, it will fundamentally reshape their roles. 83% of DevSecOps professionals believe AI will significantly change their work within five years, and notably, 76% think this will create more engineering jobs, not fewer. As coding becomes easier with AI, engineers who can architect systems, ensure quality, and apply business context will be in high demand.\n\nCritically, 88% agree there are essential human qualities that AI will never fully replace, including creativity, innovation, collaboration, and strategic vision.\n\nSo how can organizations bridge the gap between AI’s promise and the reality of fragmented workflows?\n\n## Join us at GitLab Transcend: Explore how to drive real value with agentic AI\nOn February 10, 2026, GitLab will be hosting Transcend, where we'll reveal how intelligent orchestration transforms AI-powered software development. You'll get a first look at GitLab's upcoming product roadmap and learn how teams are solving real-world challenges by modernizing development workflows with AI.\n\nOrganizations winning in this new era balance AI adoption with security, compliance, and platform consolidation. AI offers genuine productivity gains when implemented thoughtfully — not by replacing human developers, but by freeing DevSecOps professionals to focus on strategic thinking and creative innovation.\n\n[Register for Transcend today](https://about.gitlab.com/events/transcend/virtual/) to secure your spot and discover how intelligent orchestration can help your software teams stay in flow.",[25,742,743],"DevOps platform","security",{"featured":14,"template":15,"slug":745},"ai-is-reshaping-devsecops-attend-gitlab-transcend-to-see-whats-next",{"content":747,"config":758},{"title":748,"description":749,"authors":750,"heroImage":752,"date":753,"body":754,"category":11,"tags":755},"Atlassian ending Data Center as GitLab maintains deployment choice","As Atlassian transitions Data Center customers to cloud-only, GitLab presents a menu of deployment choices that map to business needs.",[751],"Emilio Salvador","https://res.cloudinary.com/about-gitlab-com/image/upload/v1750098354/Blog/Hero%20Images/Blog/Hero%20Images/blog-image-template-1800x945%20%281%29_5XrohmuWBNuqL89BxVUzWm_1750098354056.png","2025-10-07","Change is never easy, especially when it's not your choice. Atlassian's announcement that [all Data Center products will reach end-of-life by March 28, 2029](https://www.atlassian.com/blog/announcements/atlassian-ascend), means thousands of organizations must now reconsider their DevSecOps deployment and infrastructure. But you don't have to settle for deployment options that don't fit your needs. GitLab maintains your freedom to choose — whether you need self-managed for compliance, cloud for convenience, or hybrid for flexibility — all within a single AI-powered DevSecOps platform that respects your requirements.\n\nWhile other vendors force migrations to cloud-only architectures, GitLab remains committed to supporting the deployment choices that match your business needs. Whether you're managing sensitive government data, operating in air-gapped environments, or simply prefer the control of self-managed deployments, we understand that one size doesn't fit all.\n\n## The cloud isn't the answer for everyone\n\nFor the many companies that invested millions of dollars in Data Center deployments, including those that migrated to Data Center [after its Server products were discontinued](https://about.gitlab.com/blog/atlassian-server-ending-move-to-a-single-devsecops-platform/), this announcement represents more than a product sunset. It signals a fundamental shift away from customer-centric architecture choices, forcing enterprises into difficult positions: accept a deployment model that doesn't fit their needs, or find a vendor that respects their requirements.\n\nMany of the organizations requiring self-managed deployments represent some of the world's most important organizations: healthcare systems protecting patient data, financial institutions managing trillions in assets, government agencies safeguarding national security, and defense contractors operating in air-gapped environments.\n\nThese organizations don't choose self-managed deployments for convenience; they choose them for compliance, security, and sovereignty requirements that cloud-only architectures simply cannot meet. Organizations operating in closed environments with restricted or no internet access aren't exceptions — they represent a significant portion of enterprise customers across various industries.\n\n![GitLab vs. Atlassian comparison table](https://res.cloudinary.com/about-gitlab-com/image/upload/v1759928476/ynl7wwmkh5xyqhszv46m.jpg)\n\n## The real cost of forced cloud migration goes beyond dollars\n\nWhile cloud-only vendors frame mandatory migrations as \"upgrades,\" organizations face substantial challenges beyond simple financial costs:\n\n* **Lost integration capabilities:** Years of custom integrations with legacy systems, carefully crafted workflows, and enterprise-specific automations become obsolete. Organizations with deep integrations to legacy systems often find cloud migration technically infeasible.\n\n* **Regulatory constraints:** For organizations in regulated industries, cloud migration isn't just complex — it's often not permitted. Data residency requirements, air-gapped environments, and strict regulatory frameworks don't bend to vendor preferences. The absence of single-tenant solutions in many cloud-only approaches creates insurmountable compliance barriers.\n\n* **Productivity impacts:** Cloud-only architectures often require juggling multiple products: separate tools for planning, code management, CI/CD, and documentation. Each tool means another context switch, another integration to maintain, another potential point of failure. GitLab research shows [30% of developers spend at least 50% of their job maintaining and/or integrating their DevSecOps toolchain](https://about.gitlab.com/developer-survey/). Fragmented architectures exacerbate this challenge rather than solving it.\n\n## GitLab offers choice, commitment, and consolidation\n\nEnterprise customers deserve a trustworthy technology partner. That's why we've committed to supporting a range of deployment options — whether you need on-premises for compliance, hybrid for flexibility, or cloud for convenience, the choice remains yours. That commitment continues with [GitLab Duo](https://about.gitlab.com/gitlab-duo-agent-platform/), our AI solution that supports developers at every stage of their workflow.\n\nBut we offer more than just deployment flexibility. While other vendors might force you to cobble together their products into a fragmented toolchain, GitLab provides everything in a **comprehensive AI-native DevSecOps platform**. Source code management, CI/CD, security scanning, Agile planning, and documentation are all managed within a single application and a single vendor relationship.\n\nThis isn't theoretical. When Airbus and [Iron Mountain](https://about.gitlab.com/customers/iron-mountain/) evaluated their existing fragmented toolchains, they consistently identified challenges: poor user experience, missing functionalities like built-in security scanning and review apps, and management complexity from plugin troubleshooting. **These aren't minor challenges; they're major blockers for modern software delivery.**\n\n## Your migration path: Simpler than you think\n\nWe've helped thousands of organizations migrate from other vendors, and we've built the tools and expertise to make your transition smooth:\n\n* **Automated migration tools:** Our [Bitbucket Server importer](https://docs.gitlab.com/user/import/bitbucket_server/) brings over repositories, pull requests, comments, and even Large File Storage (LFS) objects. For Jira, our [built-in importer](https://docs.gitlab.com/user/project/import/jira/) handles issues, descriptions, and labels, with professional services available for complex migrations.\n\n* **Proven at scale:** A 500 GiB repository with 13,000 pull requests, 10,000 branches, and 7,000 tags is likely to [take just 8 hours to migrate](https://docs.gitlab.com/user/import/bitbucket_server/) from Bitbucket to GitLab using parallel processing.\n\n* **Immediate ROI:** A [Forrester Consulting Total Economic Impact™ study commissioned by GitLab](https://about.gitlab.com/resources/study-forrester-tei-gitlab-ultimate/) found that investing in GitLab Ultimate confirms these benefits translate to real bottom-line impact, with a three-year 483% ROI, 5x time saved in security related activities, and 25% savings in software toolchain costs.\n\n## Start your journey to a unified DevSecOps platform\n\nForward-thinking organizations aren't waiting for vendor-mandated deadlines. They're evaluating alternatives now, while they have time to migrate thoughtfully to platforms that protect their investments and deliver on promises.\n\nOrganizations invest in self-managed deployments because they need control, compliance, and customization. When vendors deprecate these capabilities, they remove not just features but the fundamental ability to choose environments matching business requirements.\n\nModern DevSecOps platforms should offer complete functionality that respects deployment needs, consolidates toolchains, and accelerates software delivery, without forcing compromises on security or data sovereignty.\n\n[Talk to our sales team](https://about.gitlab.com/sales/) today about your migration options, or explore our [comprehensive migration resources](https://about.gitlab.com/move-to-gitlab-from-atlassian/) to see how thousands of organizations have already made the switch.\n\nYou also can [try GitLab Ultimate with GitLab Duo Enterprise](https://about.gitlab.com/free-trial/devsecops/) for free for 30 days to see what a unified DevSecOps platform can do for your organization.",[577,26,756,757],"product","features",{"featured":14,"template":15,"slug":759},"atlassian-ending-data-center-as-gitlab-maintains-deployment-choice",{"promotions":761},[762,776,787,798],{"id":763,"categories":764,"header":766,"text":767,"button":768,"image":773},"ai-modernization",[765],"ai-ml","Is AI achieving its promise at scale?","Quiz will take 5 minutes or less",{"text":769,"config":770},"Get your AI maturity score",{"href":771,"dataGaName":772,"dataGaLocation":247},"/assessments/ai-modernization-assessment/","modernization assessment",{"config":774},{"src":775},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138786/qix0m7kwnd8x2fh1zq49.png",{"id":777,"categories":778,"header":779,"text":767,"button":780,"image":784},"devops-modernization",[756,11],"Are you just managing tools or shipping innovation?",{"text":781,"config":782},"Get your DevOps maturity score",{"href":783,"dataGaName":772,"dataGaLocation":247},"/assessments/devops-modernization-assessment/",{"config":785},{"src":786},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138785/eg818fmakweyuznttgid.png",{"id":788,"categories":789,"header":790,"text":767,"button":791,"image":795},"security-modernization",[743],"Are you trading speed for security?",{"text":792,"config":793},"Get your security maturity score",{"href":794,"dataGaName":772,"dataGaLocation":247},"/assessments/security-modernization-assessment/",{"config":796},{"src":797},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138786/p4pbqd9nnjejg5ds6mdk.png",{"id":799,"paths":800,"header":803,"text":804,"button":805,"image":810},"github-azure-migration",[801,802],"migration-from-azure-devops-to-gitlab","integrating-azure-devops-scm-and-gitlab","Is your team ready for GitHub's Azure move?","GitHub is already rebuilding around Azure. Find out what it means for you.",{"text":806,"config":807},"See how GitLab compares to GitHub",{"href":808,"dataGaName":809,"dataGaLocation":247},"/compare/gitlab-vs-github/github-azure-migration/","github azure migration",{"config":811},{"src":786},{"header":813,"blurb":814,"button":815,"secondaryButton":820},"Start building faster today","See what your team can do with the intelligent orchestration platform for DevSecOps.\n",{"text":816,"config":817},"Get your free trial",{"href":818,"dataGaName":54,"dataGaLocation":819},"https://gitlab.com/-/trial_registrations/new?glm_content=default-saas-trial&glm_source=about.gitlab.com/","feature",{"text":510,"config":821},{"href":58,"dataGaName":59,"dataGaLocation":819},1777493587409]