3

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?

kebs
  • 6,387
  • 4
  • 41
  • 70
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • 3
    You call `vec.at(10)` -> it throws the exception `std::out_of_range` -> you say that you expect the exception `std::logic_error` to be thrown -> `std::out_of_range` *is* `std::logic_error` because it's a subtype of it -> everything's fine – milleniumbug Mar 02 '16 at 20:40

1 Answers1

9

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.

melak47
  • 4,772
  • 2
  • 26
  • 37