Search code examples
c++c++11googletest

Why are `SetUp`/`TearDown` virtual in gtest?


In the googletest Primer, there is an example, where the SetUp/TearDown are virtual. Can someone explain why they are virtual? Here is an example verbatim from the primer:

class QueueTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    q1_.Enqueue(1);
    q2_.Enqueue(2);
    q2_.Enqueue(3);
  }

  // virtual void TearDown() {}

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(0, q0_.size());
}

I wonder why not writing it as follows. Will the behavior change?

class QueueTest : public ::testing::Test {
 protected:
  void SetUp() override {
    q1_.Enqueue(1);
    q2_.Enqueue(2);
    q2_.Enqueue(3);
  }

  // void TearDown() override {}

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(0, q0_.size());
}

Solution

  • Given than both SetUp and TearDown are declared virtual in parent class, all three declaration in subclasses are equivalent:

    virtual void SetUp() {}
    void SetUp() {}
    void SetUp() override {}
    

    I'd stick to using override, as any typo (like void setUp() override) would cause compilation error.

    As override keyword was only introduced in C++11 and google test framework was created before it was available, I assume that override is not used in documentation because simply no one bothered to update it.