“捕获"单元测试框架-REQUIRE_THROWS_AS [英] "Catch" unit testing framework - REQUIRE_THROWS_AS
问题描述
我开始使用"Catch"单元测试框架,到目前为止,它确实很棒.我曾经非常痛苦地使用VS内置的单元测试框架.
I started to use "Catch" unit testing framework and so far it's really great. I have used VS built in unit testing framwork with great pain .
我注意到宏REQUIRE_THROWS_AS
的行为不符合人们的预期
one thing I have noticed that the macro REQUIRE_THROWS_AS
does not behave as one would expect
来自文档:
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);
}
}
我希望测试失败,但是它说测试通过了.框架中是否存在错误或我错了?
I expect the test to fail and yet it says the test passed. is there a bug in the framework or I am wrong?
推荐答案
std::out_of_range
(这是vector::at
应该在此处抛出的内容)是从std::logic_error
派生的:
std::out_of_range
(which is what vector::at
should throw here) is derived from 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 :
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
, andstd::experimental::bad_optional_access
are derived fromstd::logic_error
. -- cppreference:
REQUIRE_THROWS_AS
可能会执行以下操作:
REQUIRE_THROWS_AS
likely does something like:
try { expression; }
catch (const exception_type&) { SUCCEED("yay"); return; }
catch (...) { FAIL("wrong exception type"); return; }
FAIL("no exception");
由于异常的多态性,断言得以通过.
And due to the polymorphic nature of exceptions, the assertion passes.
这篇关于“捕获"单元测试框架-REQUIRE_THROWS_AS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!