"Catch" 单元测试框架 - REQUIRE_THROWS_AS

"Catch" unit testing framework - REQUIRE_THROWS_AS

我开始使用 "Catch" 单元测试框架,到目前为止它真的很棒。我曾经非常痛苦地使用 VS 内置的单元测试框架。

有一件事我注意到宏 REQUIRE_THROWS_AS 的行为并不像人们预期的那样

来自文档:

REQUIRE_THROWS_AS( expression, exception type ) and
CHECK_THROWS_AS( expression, exception type )

Expects that an exception of the specified type is thrown during evaluation of the expression.

当我尝试写

TEST_CASE("some test") {
    SECTION("vector throws") {
        std::vector<int> vec;
        REQUIRE_THROWS_AS(vec.at(10), std::logic_error);
    }
}

我预计测试会失败,但它却说测试通过了。是框架有bug还是我错了?

std::out_of_range(这是 vector::at 应该抛出的)派生自 std::logic_error:

No standard library components throw this exception directly, but the exception types std::invalid_argument, std::domain_error, std::length_error, std::out_of_range, std::future_error, and std::experimental::bad_optional_access are derived from std::logic_error. -- cppreference:

REQUIRE_THROWS_AS 可能会做类似的事情:

try { expression; } 
catch (const exception_type&) { SUCCEED("yay"); return; }
catch (...) { FAIL("wrong exception type"); return; }
FAIL("no exception");

并且由于异常的多态性,断言通过。