yegor256
yegor256

Reputation: 105053

How can I catch my custom exception with Boost.Test?

When I'm testing my C++ class with Boost.Test and my custom exceptions are thrown (they are instances of my class), this is the message I see in log:

unknown location:0: fatal error in "testMethod": unknown type

It's very un-informative and I don't know how to teach Boost.Test to convert my exception to string and display it properly. My Exception class has operator string(), but it doesn't help. Any ideas? Thanks!

Upvotes: 3

Views: 1921

Answers (4)

yegor256
yegor256

Reputation: 105053

I just inherited it from std::string and everything works fine.

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76788

I believe it would work if your custom exception class inherited from std::exception.

Upvotes: 2

Lars
Lars

Reputation: 1466

You can test if a function throw a specified except by using BOOST_CHECK_THROW or similar

see Boost.Test Docs:

class my_exception{};

BOOST_AUTO_TEST_CASE( test )
{
   int i =  0;
   BOOST_CHECK_THROW( i++, my_exception );
}

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100648

You may need to define an operator<< in the std namespace:

namespace std {
    inline std::ostream& operator<<(std::ostream& os, const Exception& ex) {
        os << ex.string();
        return os;
    }
}

This should allow boost.test to display the contents of your exception.

I've found this necessary so that objects can be tested with BOOST_CHECK_EQUAL(), etc.

Upvotes: 0

Related Questions