问题
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 .
one thing I have noticed that the macro REQUIRE_THROWS_AS
does not behave as one would expect
from the docs:
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.
when I try to write
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?
回答1:
std::out_of_range
(which is what vector::at
should throw here) is derived from 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
, andstd::experimental::bad_optional_access
are derived fromstd::logic_error
. -- cppreference:
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.
来源:https://stackoverflow.com/questions/35757334/catch-unit-testing-framework-require-throws-as