【问题标题】:Boost test expected throw升压测试预期投掷
【发布时间】:2014-11-18 16:08:48
【问题描述】:

我对需要引发异常的代码部分进行了测试,但使用 BOOST_CHECK_THROW 仍然会使测试崩溃。这是测试:

#include <boost/test/unit_test.hpp>

#include "tools/CQueueMessage.hpp"

class TestMessage
{
public:
    std::string m_message1;
    std::string m_message2;
    std::string m_messageEmpty;
    std::string m_messageEmptyJson;

    TestMessage()
    :   m_message1("{\"photo\":{\"name\":\"pic\",\"extension\":\"jpg\"}}"),
        m_message2("{\"photo\":{\"name\":\"pic\",\"extension\":\"png\"}}"),
        m_messageEmpty(""), m_messageEmptyJson("{}") {}
    ~TestMessage() {}
};

BOOST_FIXTURE_TEST_CASE(message2send, TestMessage)
{
    QueueMessage qmsg1(m_message1);
    BOOST_CHECK_EQUAL(qmsg1.messageToBeSent(), "{\"photo\":{\"name\":\"pic\",\"extension\":\"jpg\"}}");

    QueueMessage qmsg2(m_message2);
    BOOST_CHECK_EQUAL(qmsg2.messageToBeSent(), "{\"photo\":{\"name\":\"pic\",\"extension\":\"png\"}}");

    BOOST_CHECK_THROW(QueueMessage qmsg3(m_messageEmpty), QueueMessageException)
//  QueueMessage qmsg4(m_messageEmptyJson);
}

QueueMessage 类构造函数在消息为空或为空 json 时抛出 QueueMessageException。我的问题是这个测试正在打印:

Running 1 test case...
unknown location(0): fatal error in "message2send": std::exception: Bad message format

*** 1 failure detected in test suite "main"
*** Exited with return code: 201 ***

如何验证是否抛出异常?


这是构造函数:

QueueMessage(CString& messageIn)
{
    std::stringstream ss;
    ss << messageIn;
    PTree pt;
    json::read_json(ss, pt);
    std::string photo = pt.get< std::string >("photo");
    if (photo.empty())
    {
        throw QueueMessageException("Bad message format"); // in debugging it arrives here
    }
}

【问题讨论】:

  • 奇怪的是 read_json 应该已经抛出,但有不同的错误消息。而对于 emptyJson 测试,这个 pt.get() 变体也应该抛出,但又是一个不同的错误消息。
  • 您可以在构造函数中和 throw 之前设置一个断点,然后在调试器中运行它。您可以将 boost 宏替换为显式的 try catch,对 QueueMessageException、const QueueMessageException&、std::exception 使用单独的 catch。如果你想控制异常,构造函数应该捕获所有内容,然后抛出自己的 QueueMessageException。
  • 好吧,我已经尽量不贴整个代码了,看来是孩子的问题……第一次调用构造函数就抛出了异常。

标签: c++ unit-testing boost


【解决方案1】:

我的心理调试能力告诉我,你的构造函数实际上并没有抛出 QueueMessageException。看起来它(通过函数 message2send)正在抛出 std::exception 或它的不同子代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2011-03-13
    • 1970-01-01
    • 2016-05-11
    • 2015-01-17
    相关资源
    最近更新 更多