- GitHub - catchorg/Catch2: A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
Like most test frameworks, Catch2 supports a class-based fixture mechanism, where individual tests are methods on class and setup/teardown can be done in constructor/destructor of the type.
However, their use in Catch2 is rare, because idiomatic Catch2 tests instead use sections to share setup and teardown code between test code. This is best explained through an example (code):
TEST_CASE is executed from the start. This means that each section is entered with a freshly constructed vector
v, that we know has size 5 and capacity at least 5, because the two assertions are also checked before the section is entered. Each run through a test case will execute one, and only one, leaf section.
REQUIRE: Stop at failure
CHECK: Continue at failure
To create a fixture:
- Derive a class from
::testing::Test. Start its body with
protected:, as we’ll want to access fixture members from sub-classes.
- Inside the class, declare any objects you plan to use.
- If necessary, write a default constructor or
SetUp()function to prepare the objects for each test. A common mistake is to spell
Setup()with a small
overridein C++11 to make sure you spelled it correctly.
- If necessary, write a destructor or
TearDown()function to release any resources you allocated in
SetUp(). To learn when you should use the constructor/destructor and when you should use
SetUp()/TearDown(), read the FAQ.
- If needed, define subroutines for your tests to share.
The rule of thumb is to use
EXPECT_* when you want the test to continue to reveal more errors after the assertion failure, and use
ASSERT_* when continuing after failure doesn’t make sense.