Search code examples
repeatgoogletest

How to repeat a test running only once Global Set-Up/Tear-Down or SetUpTestSuite / TearDownTestSuite


I have a test suite setup that takes some time to run. (Open a serial port initialize communication with a board, etc).

I would like to run a test in a loop, but without running this setups and cleanups every time because they are not needed, and only consume time.

The default behavior of TestSuiteSetup is to be executed once and then allow any number of tests from that suite to run. Running multiple tests in a suite or repeating one test are actually the same use case, but it seems not to be supported by -repeat. (I would expect it to be possible to combine the flag with an option like: -run_setup_only_once)

Is this possible in gtest? Or is there another way to achieve this?


Solution

  • How about using a global object of some form to indicate if it is the first repetition or not? Below is a simple example:

    #include <iostream>
    
    #include "gtest/gtest.h"
    
    bool g_first_iteration = true;
    
    class FooTest : public testing::Test {
     protected:
      static void SetUpTestSuite() {
        std::cout << "========Beginning of all tests========" << std::endl;
    
        // This part is run only in the first iteration.
        if (g_first_iteration) {
          g_first_iteration = false;
          std::cout << ">>>>>>>> First time setup <<<<<<<<< " << std::endl;
        }
      }
    };
    
    TEST_F(FooTest, Test1) { EXPECT_EQ(1, 1); }
    

    You can check the output here: https://godbolt.org/z/71eE34bff