“捕获"单元测试框架-REQUIRE_THROWS_AS [英] "Catch" unit testing framework - REQUIRE_THROWS_AS

查看:213
本文介绍了“捕获"单元测试框架-REQUIRE_THROWS_AS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用"Catch"单元测试框架,到目前为止,它确实很棒.我曾经非常痛苦地使用VS内置的单元测试框架.

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 .

我注意到宏REQUIRE_THROWS_AS的行为不符合人们的预期

one thing I have noticed that the macro REQUIRE_THROWS_AS does not behave as one would expect

来自文档:

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);
    }
}

我希望测试失败,但是它说测试通过了.框架中是否存在错误或我错了?

I expect the test to fail and yet it says the test passed. is there a bug in the framework or I am wrong?

推荐答案

std::out_of_range(这是vector::at应该在此处抛出的内容)是从std::logic_error派生的:

std::out_of_range (which is what vector::at should throw here) is derived from std::logic_error:

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

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可能会执行以下操作:

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.

这篇关于“捕获"单元测试框架-REQUIRE_THROWS_AS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆