Search code examples
googletest

What's the best way to guard some assertions with another assertion?


Let's say I have this code, which is only part of my test case:

ASSERT_EQ( 1, p.polygon().num_vertices() );
EXPECT_EQ( blah, p.polygon().at( 0 ) );

I really don't want:

  • The overhead of moving each of these little bits to separate functions.
  • To repeat the predicate in the first assertion.
  • To abort the entire test case if the first assertion fails.

...but of course, I'd better not try the second assertion if the first fails. What's the best way to do this?


Solution

  • If C++11 is available, a lambda can be used to scope a set of assertions without the full overhead of a separate function:

    [=]() {
      ASSERT_EQ( 1, p.polygon().num_vertices() );
      EXPECT_EQ( blah, p.polygon().at( 0 ) );
    }();
    

    This can appear inline in the test case (unlike a full function), doesn't need to be named, and looks more or less like a scope block (good). Obviously, a fatal assertion in such a block will only exit the block, so it's not ideal if the grouped assertions include one that needs to abort the entire test case.