1

I am testing a function that returns an integer error code. I am using BOOST_CHECK_EQUAL to compare the functions return to the error code. Similar to this:

BOOST_CHECK_EQUAL( foo(a), 12 ) // where 12 is an error code

The function foo has a cerr statement in it that will be triggered before the error code is returned. Is there any way to hide the error message? Currently my output reads something like this:

Running 7 test cases...
Error in foo()

*** No errors detected

but I want:

Running 7 test cases...

*** No Errors detected

Is there a way to run this test with the equivalent of a 2>/dev/null on just that one test? Thanks ahead of time.

Cory-G
  • 1,025
  • 14
  • 26

1 Answers1

1

One option is to save the return value in a variable so the side-effect is triggered before the check:

auto result = foo(a);
BOOST_CHECK_EQUAL(result, 12)

Another which hides the output, is to change the buffer of std::cerr to write to dev/null:

namespace ns {
    struct defer_output_wrapper
    {
        defer_output_wrapper(std::ostream& os) : os(os), sbuf(os.rdbuf())
        {
            os.rdbuf(null.open("dev/null", std::ios_base::out));
        }

        ~defer_output_wrapper() { os.rdbuf(sbuf); }
    private:
        std::ostream& os;
        std::streambuf* sbuf;
        std::filebuf null;
    };
}

Later on...

{
    ns::defer_output_wrapper _(std::cerr); // Output on std::cerr writes to dev/null
    BOOST_CHECK_EQUAL(foo(a), 12)
} // buffer changes back
David G
  • 94,763
  • 41
  • 167
  • 253
  • I want to have the error not show up at all, so the first suggestion won't work too well. (This is a very large program with lots of test cases, I want no output on success.) I may use your second solution as I am using a logger and can just change the output priority before the check and then revert it after. I was just wondering if there was a boost-test-native way to do it. It seems like it should be a common thing, to want to hide output while testing. I can't find any google results on it, so it must not be. – Cory-G Jul 07 '14 at 22:14