C++ 助推测试预期投掷

C++ 助推测试预期投掷,c++,unit-testing,boost,C++,Unit Testing,Boost,我对需要抛出异常的代码部分进行了测试,但是使用BOOST\u CHECK\u 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_messageEm

我对需要抛出异常的代码部分进行了测试,但是使用
BOOST\u CHECK\u 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(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
    }
}
QueueMessage(CString&messageIn)
{
std::stringstream-ss;
ss(“照片”);
if(photo.empty())
{
抛出QueueMessageException(“错误消息格式”);//在调试过程中,它到达此处
}
}

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

奇怪的是
read\u json
应该已经抛出了,但有不同的错误消息。对于emptyJson测试,这个
pt.get()。您可以使用一个显式的try catch替换boost宏,为QueueMessageException、const QueueMessageException和std::exception使用单独的catch。如果你想控制异常,构造函数应该捕获所有内容,然后抛出自己的QueueMessageException。。。它在构造函数的第一次调用中抛出异常。
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
    }
}