“Catch” unit testing framework - REQUIRE_THROWS_AS

这一生的挚爱 提交于 2020-01-04 07:52:43

问题


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, 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.



来源:https://stackoverflow.com/questions/35757334/catch-unit-testing-framework-require-throws-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!