Search code examples
c++googletest

catch a gtest EXPECT statement failure


I have a test helper function containing various gtest expect e.g. EXPECT_TRUE(). I have a couple tests that I intentionally want to fail. Rather than complicating the test helper function parameters, is there a simple way to ignore the asserts for these specific tests? For example using a try/catch in the case of an exception.

#include <gtest/gtest.h>

class Foo: public testing::Test
{
  // fixture things...
};

void test_helper(bool val_a)
{
  EXPECT_TRUE(val_a);
  // more EXPECT validation goes here
}

TEST_F(Foo, failing_test)
{
    // can this next line be wrapped to expect a failure?
    test_helper(this, false);
}

Solution

  • near the top of the testing/testing.h file there is the AssertionResult class with the description

    "A class for indicating whether an assertion was successful..."

    The only part of the original helper function signature that needs changing is the return statement.

    testing::AssertionResult test_helper(bool val_a)
    {
      if (!val_a)
      {
        return testing::AssertionFailure() << "custom error message...";
      }
      // more validation goes here
      return testing::AssertionSuccess();
    }
    
    TEST_F(Foo, failing_test)
    {
        // This test now passes
        ASSERT_FALSE(test_helper(this, false));
    }