21

I'm running google test.

I need something like Before class. I have the SetUp() and TearDown() functions, but they run before and after each test. Now I need something global - like ctor, that should run only one time when the class loaded.

Kara
  • 6,115
  • 16
  • 50
  • 57
Rat
  • 357
  • 2
  • 5
  • 16
  • Please elaborate on this "one time when the class is loaded". What class are you referring to, and what does class "loading" mean? – Marko Popovic Mar 07 '16 at 14:14
  • I mean something that run before **all** tests start. not setup for each test case. – Rat Mar 07 '16 at 14:26

2 Answers2

29

You can define static member functions void SetUpTestCase() and void TearDownTestCase() in each of your fixture classes, i.e. in each class derived from ::testing::Test.

That code will run only once for each fixture, before and after all test in the fixture are run.

Check the docs.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Antonio Pérez
  • 6,702
  • 4
  • 36
  • 61
  • Perez - How can I do it for all the tests (in all test cases) ? I mean that I wish that before each test the same SetUp method will run as well as that after each test the same TearDown method will run, without adding/editing any existing class ? – Guy Avraham Jun 25 '17 at 09:01
  • 2
    @GuyAvraham: AFAIK there is no such hook function in the framework that allows you to do this. You'd need to build it yourself by maybe defining a child class for `::testing::Test` and then making your test classes derive from it instead. – Antonio Pérez Jun 27 '17 at 10:19
  • 6
    Please note that in newer versions of gtest you might need to use `SetUpTestSuite()` and `TearDownTestSuite()` methods instead. – pooya13 Feb 06 '19 at 21:06
  • if you want global first-time initialization, just can use a static mutex and static bool to init for the only first time. But not sure for last-time global teardown. – Mohan Kumar Feb 07 '19 at 18:36
13

Inherit from class ::testing::Environment and override methods SetUp and TearDown, these methods will contain code for your global setup and tear down. Then, in the main function of executable that runs you tests, call function ::testing::AddGlobalTestEnvironment() before calling RUN_ALL_TESTS(). For more information, check the documentation:

https://github.com/google/googletest/blob/master/docs/advanced.md#global-set-up-and-tear-down

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Marko Popovic
  • 3,999
  • 3
  • 22
  • 37
  • 2
    Page has moved -> https://github.com/google/googletest/blob/master/docs/advanced.md#global-set-up-and-tear-down – Den-Jason Mar 18 '21 at 09:52