Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Catch" unit testing framework - REQUIRE_THROWS_AS

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?

like image 575
David Haim Avatar asked Nov 07 '25 14:11

David Haim


1 Answers

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, and std::experimental::bad_optional_access are derived from std::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.

like image 121
melak47 Avatar answered Nov 09 '25 09:11

melak47