开发者

How to combine boost::exception with boost::unit_test and have a nice message

开发者 https://www.devze.com 2023-02-18 19:47 出处:网络
When I have the following auto test case : class MyException: virtual public boost::exception, virtual public std::exception

When I have the following auto test case :

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

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

Running the test gives:

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

How can I change this so the name of the exception (MyException) and boost::diagnostic_information() is shown instead of std::exception ? I tried registering 开发者_开发技巧my own exception translator to the execution monitor but it seems std::exception is handled before any registered translator is tried.

I am using boost 1.44 and gcc 4.4.5 on Linux.


I found how to do this:

Use a global fixture like so:

#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 )

Then the following test:

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

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

Gives:

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号