提升测试预期投掷

时间:2014-11-18 16:08:48

标签: c++ unit-testing boost

我对需要抛出异常的代码部分进行了测试,但使用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);
}

如果消息为空或者是空的json,QueueMessage类构造函数将抛出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
    }
}

1 个答案:

答案 0 :(得分:2)

我的通灵调试能力告诉我你的构造函数实际上并没有抛出QueueMessageException。看起来它(通过函数message2send)抛出std::exception或它的另一个孩子。