Search code examples
c++testingcatch2

How to check the same condition in several Catch2 test cases


I have to check the some condition (eg. initial state) in several test cases. I cannot use CHECK in function and I would like to replace the current macro if possible.

#include "catch.hpp"

#define CHECK_INITIAL_STATE() \
    CHECK(first_condition); \
    CHECK(second_condition);

TEST_CASE("first_test") {
    CHECK_INITIAL_STATE();
    // do something
    // restore state
    CHECK_INITIAL_STATE();
}

Solution

  • Catch2 comes with this feature built-in in a very elegant way:

    TEST_CASE("first_test") {
        CHECK(first_condition);
        CHECK(second_condition);
    
        SECTION("do something 1") {
            // this test is executed after the code outside of the section
        }
        SECTION("do something 2") {
            // this test is executed after the code outside of the section
            // but without executing the previous section
        }
    }