"Catch"单元测试框架 - REQUIRE_THROWS_AS

3

我开始使用“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);
    }
}

我本来以为测试会失败,但它却显示测试通过了。是框架出了问题还是我错了?


3
您调用vec.at(10) -> 抛出异常std::out_of_range -> 您认为应该抛出异常std::logic_error -> std::out_of_range std::logic_error 的子类型,所以一切都没问题。 注意:此翻译仅供参考,如果需要精确的技术翻译,请咨询专业的翻译人员或技术人员。 - milleniumbug
1个回答

9
(这就是vector::at应该抛出的异常)源自:

没有标准库组件会直接引发此异常,但异常类型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");

由于异常具有多态性,断言所通过。

2
我错过了 logic_errorout_of_range 基类的那部分内容。谢谢。 - David Haim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接