我有以下使用最新(2.4.0)版本的 Catch2 运行的代码:
#include "catch.hpp"
#include <iostream>
TEST_CASE("Test") {
int x = 0;
SECTION("A") {
std::cout << "A";
++x;
REQUIRE(x == 1);
}
SECTION("B") {
std::cout << "B";
++x;
REQUIRE(x == 1);
}
std::cout << "X\n";
REQUIRE(x == 1);
}
如果我运行它,一切都会按预期工作,我得到:
AX
BX
=================================================================
All tests passed (4 assertions in 1 test case)
显然,测试用例运行了两次,每个部分运行一次。
如果我在其中一个部分更改断言REQUIRE(x == 0)
,再次说,一切都按预期工作,Catch2 运行每个部分一次并告诉我第一个失败。REQUIRE(x == 0)
但是,如果我在两个部分中都将断言更改为,结果会令人困惑(我稍微缩短了它):
A
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.out is a Catch v2.4.0 host application.
Run with -? for options
---------------------------------------------------------------------
Test
A
---------------------------------------------------------------------
test.cpp:10: FAILED:
REQUIRE( x == 0 )
with expansion:
1 == 0
B--------------------------------------------------------------------
Test
B
---------------------------------------------------------------------
test.cpp:15: FAILED:
REQUIRE( x == 0 )
with expansion:
1 == 0
X
---------------------------------------------------------------------
Test
---------------------------------------------------------------------
test.cpp:19: FAILED:
REQUIRE( x == 1 )
with expansion:
0 == 1
=====================================================================
test cases: 1 | 1 failed
assertions: 3 | 3 failed
测试显然运行了 3 次,最后一次绕过了这两个部分。这种行为是预期的吗?我曾尝试查看 Catch2 文档,但找不到任何相关内容。