einpoklum
einpoklum

Reputation: 132290

How to best make my catch2 CHECK() output more informative about what it checks?

I am working on some code with unit tests using catch2 (and it will stay that way, for reasons).

Now, in the set of unit tests, there are a lot of (pairs of) lines which look like this:

  T t1;
  t1 = foo(some, params, here);
  CHECK(my_compare(t1, T{some_literal}));

so, a single function call is used to set t1, then the result is compared to a T literal.

Now, when this runs and fails, I get:

/path/to/test.cpp:493: Failure:
  CHECK(my_compare(t1, T{some_literal}));
with expansion:
  false

but obviously I don't get the "some, params, here". Well, I need it. Otherwise, I don't really know which test failed without reading the source code.

Since there's a reliance on macros here, I can't just wrap CHECK() in a function and do something fancy inside.

What would you suggest I do to make "some, params, here" get printed alongside "some_literal" when the check fails, while:

  1. Keeping my test source code terse.
  2. Not repeating myself
  3. Still getting a valid file and line number

?

Note: The currently-used version of catch2 is 2.7.0, merged into a single header. If a version change would help, that may be doable.

Upvotes: 3

Views: 5684

Answers (1)

Elmar Zander
Elmar Zander

Reputation: 1516

Use the CAPTURE or INFO logging macros (see https://github.com/catchorg/Catch2/blob/devel/docs/logging.md#streaming-macros).

CAPTURE(some);
CAPTURE(params);
CAPTURE(here);

or

INFO("Params: some="<<some<<", params="<<params<<", here="<<here);

should do the trick.

BTW CAPTURE only logs variables that were captured in the same section as the failed test. Example:

    SECTION("foo"){
        int i = 1;
        CAPTURE(i);
        CHECK(i==1);
    }
    SECTION("bar"){
        int j = 2;
        CAPTURE(j);
        CHECK(j==1);
    }

outputs

foo.cpp:10: FAILED:
  CHECK( j==1 )
with expansion:
  2 == 1
with message:
  j := 2

Upvotes: 3

Related Questions