19

Is there a way to check that SetUp code has actually worked properly in GTest fixtures, so that the whole fixture or test-application can be marked as failed rather than get weird test results and/or have to explicitly check this in each test?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

1 Answers1

15

If you put your fixture setup code into a SetUp method, and it fails and issues a fatal failure (ASSERT_XXX or FAIL macros), Google Test will not run your test body. So all you have to write is

class MyTestCase : public testing::Test {
 protected:
  bool InitMyTestData() { ... }

  virtual void SetUp() {
    ASSERT_TRUE(InitMyTestData());
  }
};

TEST_F(MyTestCase, Foo) { ... }

Then MyTestCase.Foo will not execute if InitMyTestData() returns false. If you already have nonfatal assertions in your setup code (i.e., EXPECT_XXX or ADD_FAILURE), you can generate a fatal assertion from them by writing ASSERT_FALSE(HasFailure()); You can find more info on failure detection in the Google Test Advanced Guide wiki page.

admo
  • 51
  • 1
  • 6
VladLosev
  • 7,296
  • 2
  • 35
  • 46
  • 2
    This doesn't seem to work when using static SetUpTestCase() (later renamed to SetUpTestSuite). At least in my case all tests in the test-case are still executed even if an assertion (ASSERT_EQ) in SetUpTestCase() fails. – Zuzu Corneliu Apr 10 '19 at 08:34
  • 3
    For static SetUpTestCase (case mentioned above), the workaround would be to create a static boolean variable in the test class - e.g. static bool s_has_assert_failure - and in SetUpTestCase do s_has_assert_failure = HasFatalFailure(). Then in SetUp do ASSERT_FALSE(s_has_assert_failure). – Zuzu Corneliu Apr 10 '19 at 08:50