我开始使用“Catch”单元测试框架,到目前为止它真的很棒。我曾经非常痛苦地使用 VS 内置的单元测试框架。
有一件事我注意到宏 REQUIRE_THROWS_AS
的行为并不像人们预期的那样
来自文档:
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);
}
}
我预计测试会失败,但它却说测试通过了。是框架有问题还是我错了?
最佳答案
std::out_of_range
(vector::at
应该在此处抛出的内容)源自 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
可能会做类似的事情:
try { expression; }
catch (const exception_type&) { SUCCEED("yay"); return; }
catch (...) { FAIL("wrong exception type"); return; }
FAIL("no exception");
并且由于异常的多态性,断言通过。
关于c++ - "Catch"单元测试框架 - REQUIRE_THROWS_AS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757334/