c++ - "Catch"单元测试框架 - REQUIRE_THROWS_AS

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

我开始使用“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, and std::experimental::bad_optional_access are derived from 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");

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

关于c++ - "Catch"单元测试框架 - REQUIRE_THROWS_AS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757334/

相关文章:

c++ - C/C++远程消息队列的推荐

c++ - 如何通过 Delphi 包装器调用 C++ 函数

Angular6 ngrx : Cannot read property 'ids' of undefined

java - Mockito 何时/然后不返回预期值

vue.js - 使用 Vue 测试工具和 Jest 测试 Vuetify 表单验证

testing - 想知道如何在 jmeter 或任何其他工具中加载测试以同时测试多个登录的登录页面

c++ - 尝试向文件添加扩展名时,Rename() 函数不起作用

c++ - 如何在 C++ 中自定义文本文件的编码?

swift - 将目标导入单元测试和在目标成员中包含该文件有什么区别?

ruby-on-rails - Rails 测试自动生成密码