【问题标题】:"Catch" unit testing framework - REQUIRE_THROWS_AS“Catch”单元测试框架 - REQUIRE_THROWS_AS
【发布时间】:2016-06-15 21:40:11
【问题描述】:

我开始使用“Catch”单元测试框架,到目前为止它真的很棒。我非常痛苦地使用了 VS 内置的单元测试框架。

我注意到宏 REQUIRE_THROWS_AS 的行为与预期不同

来自文档:

REQUIRE_THROWS_AS( expression, exception type ) and
CHECK_THROWS_AS( expression, exception type )

预计在执行期间会抛出指定类型的异常 表达式的评估。

当我尝试写作时

TEST_CASE("some test") {
    SECTION("vector throws") {
        std::vector<int> vec;
        REQUIRE_THROWS_AS(vec.at(10), std::logic_error);
    }
}

我预计测试会失败,但它却说测试通过了。框架中是否有错误或我错了?

【问题讨论】:

  • 你调用vec.at(10) -> 它抛出异常std::out_of_range -> 你说你希望抛出异常std::logic_error -> std::out_of_range std::logic_error 因为它是它的一个子类型 -> 一切都很好

标签: c++ unit-testing testing catch-unit-test


【解决方案1】:

std::out_of_rangevector::at 应该在这里抛出)派生自std::logic_error

没有标准库组件直接抛出此异常,但异常类型std::invalid_argumentstd::domain_errorstd::length_errorstd::out_of_rangestd::future_errorstd::experimental::bad_optional_access派生自std::logic_error。 --cppreference:

REQUIRE_THROWS_AS 可能会执行以下操作:

try { expression; } 
catch (const exception_type&) { SUCCEED("yay"); return; }
catch (...) { FAIL("wrong exception type"); return; }
FAIL("no exception");

并且由于异常的多态性,断言通过了。

【讨论】:

  • 我错过了logic_errorout_of_range 的基类的部分。谢谢
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 2015-09-09
  • 2014-10-24
  • 2010-09-10
  • 2023-04-10
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多