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.
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);
}
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);
}
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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?