Language: CPP
Testing
Catch2 was created by Phil Nash as the successor to the original Catch framework. Its goal is to simplify unit testing in C++ by providing expressive macros, automatic test registration, and rich reporting while being lightweight and easy to integrate.
Catch2 is a modern, header-only C++ unit testing framework. It provides a simple syntax for writing test cases and assertions, making it easy to write, maintain, and execute tests for C++ projects.
sudo apt install catch2brew install catch2Download the single header from https://github.com/catchorg/Catch2/releasesCatch2 allows defining test cases with `TEST_CASE` macros and verifying conditions using `REQUIRE`, `CHECK`, and related assertions. It supports sections, tags, BDD-style tests, and integration with build systems for automated testing.
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
TEST_CASE("Factorials are computed correctly", "[factorial]") {
REQUIRE( Factorial(0) == 1 );
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
}Defines a test case to verify factorial computations using `REQUIRE` assertions.
TEST_CASE("Vectors can be sized and resized", "[vector]") {
std::vector<int> v(5);
CHECK( v.size() == 5 );
v.push_back(1);
CHECK( v.size() == 6 );
}`CHECK` allows multiple assertions in a test case without aborting on failure.
TEST_CASE("Testing different scenarios") {
SECTION("Empty vector") {
std::vector<int> v;
REQUIRE(v.empty());
}
SECTION("Non-empty vector") {
std::vector<int> v = {1,2,3};
REQUIRE(v.size() == 3);
}
}Sections allow grouping related test scenarios within a single test case.
TEST_CASE("String manipulation", "[string][manipulation]") {
REQUIRE( toUpper("abc") == "ABC" );
}Tags help in filtering and running specific subsets of tests via command line.
SCENARIO("Vectors can be resized") {
GIVEN("A vector with 3 elements") {
std::vector<int> v = {1,2,3};
WHEN("an element is added") {
v.push_back(4);
THEN("the size increases") {
REQUIRE(v.size() == 4);
}
}
}
}Demonstrates behavior-driven development style tests using `SCENARIO`, `GIVEN`, `WHEN`, and `THEN`.
Use `REQUIRE` for critical assertions and `CHECK` for non-fatal checks.
Organize tests with tags for selective execution.
Use sections to reduce code duplication for similar test scenarios.
Keep test cases small and focused on a single functionality.
Integrate Catch2 tests with CI pipelines for automated testing.