c++ - boost 测试 : catch user defined exceptions

标签 c++ unit-testing boost

如果我的代码中有用户定义的异常,我将无法进行 Boost 测试 将它们视为失败。

例如,

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(MyTest,1)
BOOST_AUTO_TEST_CASE(MyTest)
{
// code which throws user defined exception, not derived from std::exception.

}

我收到一条通用消息:

Caught exception: ....
unknown location(0):....

它不会将此错误识别为失败,因为它不是 std::exception。 所以它不遵守 expected_failures 条款。

如何强制这段代码始终抛出异常? 这似乎是一个有用的东西。以防将来代码更改导致代码 通过并且没有抛出异常,我想知道这一点。

最佳答案

EXPECTED_FAILURES 指的是针对BOOST_REQUIRE 或其他断言的失败。文档明确指出:

The feature is not intended to be used to check for expected functionality failures. To check that a particular input is causing an exception to be thrown use BOOST_CHECK_THROW family of testing tools.

重点是我的。

当断言失败但您想暂时忽略它时,预期的失败旨在用作测试期间的临时解决方法。

摘自他们的 expected failures spec :

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( my_test1, 1 )

BOOST_AUTO_TEST_CASE( my_test1 )
{
    BOOST_CHECK( 2 == 1 );
}

将导致输出

test.cpp(10): error in "my_test1": check 2 == 1 failed

Test suite "example" passed with:
  1 assertions out of 1 failed
  1 failures expected
  1 test case out of 1 passed

As you can see, in spite of assertions failing, the test case still passed due to the use of expected failures.


So if you need to verify that something is throwing an exception, you use code like the following:

BOOST_AUTO_TEST_CASE(invalid_operation_should_throw_custom_exception)
{
    MyObj obj;
    BOOST_REQUIRE_THROW(obj.invalid_operation(), CustomException);
}

关于c++ - boost 测试 : catch user defined exceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2914932/

相关文章:

c++ - 用 C++ 中的文件指针替换 stdout 和 stdin?

c++ - 此代码是从 vector 中添加和删除项目的线程安全方式吗?

c# - 模拟 UdpClient 进行单元测试

javascript - Jest messageParent 只能在工作人员内部使用

c# - 单元测试 ASP.NET Core HttpResponse.OnStarting()

c++ - boost 拆分使用率

c++简单解析带有属性树的boost xml

c++ - 代码块的 Boost 库设置

c++ - 模型观察矩阵 - C++、OpenGL

c++ - 随机 boost 独立性