boost unit test - list available tests

2019-05-04 20:02发布

问题:

I've written some scripts to automate the running of our unit tests, written using the boost unit testing framework. I'd like to add functionality to allow the selection and subsequent running of a subset of all tests. I know I can run a subset of tests using the run_test argument, but I can't find a way to list all tests that are in a compiled binary, i.e. all the argument values I can pass to run_test. Is there a way to extract all available tests, or will I have to write a custom test runner? If so, where do I start?

回答1:

Documentation for the internals of boost::test can be a bit lacking, that said everything is available.

Have a look at the boost::test header files, specifically at the test_suite and test_unit classes. There is a function called traverse_test_tree which can be used to walk through the registered tests.

Below is some samle code I have written to output test results in a specific format, it uses traverse_test_tree to output the result of each test, hopefully it will give you a head start....

/**
 * Boost test output formatter to output test results in a format that
 * mimics cpp unit.
 */
class CppUnitOpFormatter : public boost::unit_test::output::plain_report_formatter
{
public:
    /**
     * Overidden to provide output that is compatible with cpp unit.
     *
     * \param tu the top level test unit.
     * \param ostr the output stream
     */
    virtual void do_confirmation_report( boost::unit_test::test_unit const& tu, 
                                         std::ostream& ostr );
};


class CppUnitSuiteVisitor : public test_tree_visitor
{
public:
    explicit CppUnitSuiteVisitor( const string& name ) : name_( name )
    {}

    virtual void visit( const test_case& tu )
    {
        const test_results& tr = results_collector.results( tu.p_id );
        cout << name_ << "::" << tu.p_name << " : " << ( tr.passed() ? "OK\n" : "FAIL\n" );
    }
private:
    string name_;
};

// ---------------------------------------------------------------------------|
void CppUnitOpFormatter::do_confirmation_report( 
        test_unit const& tu, std::ostream& ostr )
{
    using boost::unit_test::output::plain_report_formatter;

    CppUnitSuiteVisitor visitor( tu.p_name );
    traverse_test_tree( tu, visitor );

    const test_results& tr = results_collector.results( tu.p_id );
    if( tr.passed() ) 
    {
        ostr << "Test Passed\n";
    }
    else
    {
        plain_report_formatter::do_confirmation_report( tu, ostr );
    }
}


回答2:

Trunk version of Boost.Test have command line argument to get what you need.