How do I write unit tests with GoogleTest/Catch2/Doctest?

Writing unit tests in C++ can greatly improve the reliability and maintainability of your code. Popular frameworks like GoogleTest, Catch2, and Doctest provide intuitive interfaces for creating and running tests. Below you'll find examples of how to get started with each of these frameworks.

Unit Testing with GoogleTest

To use GoogleTest, you first need to set it up in your project. After that, you can create test cases using the TEST macro.

#include // Sample function to test int Add(int a, int b) { return a + b; } // Test case TEST(AddTest, PositiveNumbers) { EXPECT_EQ(Add(1, 2), 3); EXPECT_EQ(Add(5, 6), 11); }

Unit Testing with Catch2

Catch2 is a header-only testing framework for C++. It is very easy to set up and provides a simple syntax.

#define CATCH_CONFIG_MAIN #include // Sample function to test int Subtract(int a, int b) { return a - b; } // Test case TEST_CASE("Subtracting numbers") { CHECK(Subtract(5, 2) == 3); CHECK(Subtract(10, 5) == 5); }

Unit Testing with Doctest

Doctest is another lightweight C++ testing framework. It is very fast and easy to integrate into your existing applications.

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" // Sample function to test bool IsEven(int number) { return number % 2 == 0; } // Test case TEST_CASE("Check if number is even") { CHECK(IsEven(2) == true); CHECK(IsEven(3) == false); }

With these examples, you can quickly set up unit tests in your C++ projects using GoogleTest, Catch2, or Doctest.


C++ GoogleTest Catch2 Doctest unit testing unit tests testing frameworks