如何在多个 Catch2 测试用例中检查相同的条件

How to check the same condition in several Catch2 test cases

本文关键字:检查 条件 测试用例 Catch2      更新时间:2023-10-16

我必须在几个测试用例中检查某些条件(例如初始状态(。我不能在功能中使用CHECK,如果可能的话,我想替换当前的宏。

#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();
}

Catch2 以一种非常优雅的方式内置了这个功能:

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
}
}