Ed Heal
Ed Heal

Reputation: 60037

Boost unit testing and catching exceptions

We have code that throws std::runtime_error and we are using the Boost unit testing framework.

At the moment we are using BOOST_CHECK_THROW. Unfortunately this does not check that the what message.

Is there a version of BOOST_CHECK_THROW that can check that an exception has been raised and that exception has the correct message?

Upvotes: 5

Views: 6050

Answers (1)

Fred Larson
Fred Larson

Reputation: 62123

Look into BOOST_CHECK_EXCEPTION, which allows you to specify a predicate on the exception that was thrown. Here's an example I created:

#define BOOST_TEST_MAIN
#include <boost/test/included/unit_test.hpp>

void fail()
{
    throw std::logic_error("some error message");
}

void succeed()
{
}

void wrong_msg()
{
    throw std::logic_error("some other error message");
}

bool correctMessage(const std::logic_error& ex)
{
    BOOST_CHECK_EQUAL(ex.what(), std::string("some error message"));
    return true;
}

BOOST_AUTO_TEST_CASE(case_fail)
{
    BOOST_CHECK_EXCEPTION(fail(), std::logic_error, correctMessage);
}

BOOST_AUTO_TEST_CASE(case_succeed)
{
    BOOST_CHECK_EXCEPTION(succeed(), std::logic_error, correctMessage);
}

BOOST_AUTO_TEST_CASE(case_wrong_msg)
{
    BOOST_CHECK_EXCEPTION(wrong_msg(), std::logic_error, correctMessage);
}

Output:

Running 3 test cases...
testUnitTest.cpp(31): error in "case_succeed": exception std::logic_error is expected
testUnitTest.cpp(20): error in "case_wrong_msg": check ex.what() == std::string("some error message") failed [some other error message != some error message]

*** 2 failures detected in test suite "Master Test Suite"

Upvotes: 5

Related Questions