12

In Boost.Test, how can I obtain the name of the current auto test case?

Example:

#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(MyTest)
{
  std::cerr << "Starting " << test_name << std::endl;
  // lots of code here
  std::cerr << "Ending " << test_name << std::endl;
}

In the example, I want the variable test_name to contain "MyTest".

Frank
  • 64,140
  • 93
  • 237
  • 324
  • 1
    Take a look at [this](https://groups.google.com/forum/?fromgroups=#!topic/boost-list/ZzFmu14UfeQ), so far it works for me – Adam Trhon Oct 02 '12 at 11:26

2 Answers2

23

There is an undocumented* function that may be called for that purpose. The following line will flush the name of the current test to cerr:

#include <boost/test/framework.hpp>

...

std::cerr << boost::unit_test::framework::current_test_case().p_name 
          << std::endl;

Note however that using this API does not flush the parameters in case of parametrized tests.

You might also be interested in the test checkpoints** (which seems to be what you want to do.)

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

...

BOOST_AUTO_TEST_CASE(MyTest)
{
  BOOST_TEST_CHECKPOINT("Starting");
  // lots of code here
  BOOST_TEST_CHECKPOINT("Ending");
}

EDIT

* The current_test_case() function is now documented, see the official Boost documentation.

** BOOST_TEST_CHECKPOINT was previously called BOOST_CHECKPOINT. See the Boost changelog (1.35.0).

BenC
  • 8,729
  • 3
  • 49
  • 68
Raffi
  • 3,068
  • 31
  • 33
  • However, I do not menage to use that name when I use --run_test=, can only get to run my test using wildcards, I cannot get the exact test name, weird!! – Antonio Mar 20 '14 at 16:40
  • 1
    Solved, I had to specify also the test suite, and do `--run_test=/`! – Antonio Mar 20 '14 at 17:18
  • I added a link to the documentation + the missing include. – BenC Jan 27 '16 at 07:37
  • And while I was there, I also fixed the `BOOST_CHECKPOINT` macros. – BenC Jan 27 '16 at 07:47
  • Thanks! I also hit this – Raffi Jan 27 '16 at 10:18
  • `boost::unit_test::framework::current_test_case().full_name()` is more idiomatic. https://www.boost.org/doc/libs/1_60_0/libs/test/doc/html/boost/unit_test/test_case.html#idm46165629438208-bb – alfC Mar 15 '20 at 07:28
1

A different question about suite names gives a way to extract the name rather than just printing it:

auto test_name = std::string(boost::unit_test::framework::current_test_case().p_name)
Community
  • 1
  • 1
Eponymous
  • 6,143
  • 4
  • 43
  • 43