如何将boost :: exception与boost :: unit_test结合起来,并有一个很好的消息

时间:2011-03-22 14:04:29

标签: c++ unit-testing exception boost

当我有以下自动测试用例时:

class MyException: virtual public boost::exception, 
                   virtual public std::exception 
{ 
};

BOOST_AUTO_TEST_CASE(ExceptionTest)
{
    BOOST_THROW_EXCEPTION(MyException());
}

运行测试给出:

ExceptionTest.cpp(14): fatal error in "void ExceptionTest::test_method()":
   std::exception: std::exception

如何更改此设置,以便显示例外(MyException)和boost::diagnostic_information()的名称而不是std::exception?我尝试将自己的异常翻译器注册到执行监视器,但似乎std::exception在尝试任何注册的翻译器之前得到处理。

我在Linux上使用boost 1.44和gcc 4.4.5。

1 个答案:

答案 0 :(得分:2)

我发现了如何做到这一点:

使用像这样的全局夹具:

#include "boost/test/unit_test_monitor.hpp"

class Fixture
{
    public:
        Fixture();
        ~Fixture();
};

void translateBoostException(const boost::exception &e)
{
    BOOST_FAIL(boost::diagnostic_information(e));
}

Fixture::Fixture()
{
    boost::unit_test::unit_test_monitor.register_exception_translator<boost::exception>(&translateBoostException);
}

Fixture::~Fixture()
{
}

BOOST_GLOBAL_FIXTURE( Fixture )

然后进行以下测试:

class MyException: virtual public boost::exception, 
                   virtual public std::exception 
{ 
};

BOOST_AUTO_TEST_CASE(ExceptionTest)
{
    BOOST_THROW_EXCEPTION(MyException());
}

给出:

Running 1 test case...
/home/..../SetupTestFixture.cpp(18): fatal error in "ConfigFile":
/home/..../Test.cpp(16): Throw in function void ConfigFile::test_method()
Dynamic exception type: boost::exception_detail::clone_impl<MyException>
std::exception::what: std::exception


*** 1 failure detected in test suite "ExceptionTest"