Home > Software design >  googletest SetUpTestSuite() does not run
googletest SetUpTestSuite() does not run

Time:06-16

From : https://google.github.io/googletest/advanced.html#sharing-resources-between-tests-in-the-same-test-suite . I am using 1.11 googletest version.

I am trying to utilize this feature in the following tests: Game_test.h

    class Game_test : public :: testing :: Test
{
protected:
    Game_test() = default;
    virtual ~Game_test() = default;

public:
    void SetUpTestCase()
    {
        Field field(8, 8);
        Engine engine;
        Rules rules;
        GameLogic glogic(&engine, &rules, &field);
    }
};

cpp : I expected that it will automatically run SetUpTestCase() for each TEST_F, but it does not. What I am missing?

TEST_F(Game_test, apply_rule)
{   
    field.setStatus(1, 2, true); // use of undeclared identifier.....

}

CodePudding user response:

It should be

void SetUp() override
{
    Field field(8, 8);
    Engine engine;
    Rules rules;
    GameLogic glogic(&engine, &rules, &field);
}

The referenced manual has no one entry SetUpTestCase. Where have you got it from?

CodePudding user response:

Several things:

  1. The example is SetUpTestSuite, not SetUpTestCase.
  2. SetUpTestSuite should be a static member.
  3. field should be a static member of the class if used in SetUpTestSuite.
  4. SetUpTestSuite runs once per test suite, not once per test case.
  5. If you want something to run once per test case, use SetUp, which is a non-static member function.
  6. SetUp can then manipulate non-static member variables.

See this example that shows the usage of both functions:

class Game_test : public testing::Test {
 protected:
  Game_test() = default;
  virtual ~Game_test() = default;

 public:
  static void SetUpTestSuite() {
    std::cout << "========Beginning of a test suit ========" << std::endl;
    static_field = std::string("AAAA");
  }

  void SetUp() override {
    std::cout << "========Beginning of a test ========" << std::endl;
    object_field = std::string("AAAA");
  }

  static std::string static_field;
  std::string object_field;
};

std::string Game_test::static_field;

TEST_F(Game_test, Test1) {
  EXPECT_EQ(static_field, std::string("AAAA"));
  EXPECT_EQ(object_field, std::string("AAAA"));

  // We change object_file, SetUpTestSuite cannot reset it back to "AAAA" cause
  // it only ran once.
  static_field = std::string("BBBB");

  // Although we change object_file, SetUp will reset it back to "AAAA"
  object_field = std::string("BBBB");
}

TEST_F(Game_test, Test2) {
  EXPECT_EQ(static_field, std::string("BBBB"));
  EXPECT_EQ(object_field, std::string("AAAA"));
}

Live example: https://godbolt.org/z/e6Tz1xMr1

  • Related