【问题标题】:Boost unit testing exception check failing strangelyBoost 单元测试异常检查异常失败
【发布时间】:2016-06-22 21:36:41
【问题描述】:

我基本上迷路了。我看过 Boost doc plus search on SO,但我似乎没有找到任何东西。假设一个类建模Fraction,我想在divider设置为0时抛出异常。

void Fraction::setQ(int q) {
    if (q == 0){
        throw new std::logic_error("Divider must not be null");
    }else{
         q_ = q;
    }
}

并且这段代码是用这段代码测试的

BOOST_AUTO_TEST_CASE( NonZeroDivider ){
    BOOST_CHECK_THROW(
        f->setQ(0),
        std::logic_error
    );
}

但是当 boost 应该捕获异常时,它不会并打印一个错误,然后是一个失败

unknown location(0): fatal error in "NonZeroDivider": unknown type

如果你能帮我解决这个问题,我已经尝试过 BOOST_CHECK_EXCEPTION(带有必要的版本)但不知道。总是相同的行为。谢谢!

【问题讨论】:

    标签: c++ unit-testing boost


    【解决方案1】:

    您的代码不会抛出异常 (std::logic_error),它会抛出指向动态分配异常的指针 (std::logic_error*);见throw new std::exception vs throw std::exception

    解决方法是删除 new 关键字:

    throw new std::logic_error("Divider must not be null");
          ~~~~
    

    【讨论】:

    • 非常感谢!有效。我会阅读您关注的主题:)
    猜你喜欢
    • 2013-08-12
    • 2015-12-27
    • 2014-04-09
    • 2019-04-09
    • 2013-02-26
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    相关资源
    最近更新 更多