gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:25:51 25 4
gpt4 key购买 nike

如果我的代码中有用户定义的异常,我将无法进行 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 failedTest 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com