"Catch"单元测试框架 - REQUIRE_THROWS_AS

Dav*_*aim 2 c++ testing unit-testing catch-unit-test

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

有一件事我注意到宏REQUIRE_THROWS_AS不像人们期望的那样表现

来自文档:

REQUIRE_THROWS_AS( expression, exception type ) and
CHECK_THROWS_AS( expression, exception type )
Run Code Online (Sandbox Code Playgroud)

期望在评估表达式期间抛出指定类型的异常.

当我试着写

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

我希望测试失败,但它说测试通过了.框架中有错误还是我错了?

mel*_*k47 6

std::out_of_range(这vector::at应该扔在这里)来自std::logic_error:

没有标准库组件直接抛出此异常,但异常类型std::invalid_argument,std::domain_error,std::length_error,std::out_of_range,std::future_error,和std::experimental::bad_optional_access衍生自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");
Run Code Online (Sandbox Code Playgroud)

由于异常的多态性,断言通过了.

  • 我错过了“logic_error”是“out_of_range”基类的部分。谢谢 (2认同)