Unit testing C++ SetUp() and TearDown()

user2785929 picture user2785929 · Sep 25, 2014 · Viewed 32.1k times · Source

I'm currently learning unit testing with google mock What is the usual use of virtual void SetUp() and virtual void TearDown() in the google mock? An example scenario with codes would be good.

Answer

phtrivier picture phtrivier · Sep 25, 2014

It's there to factor code that you want to do at the beginning and end of each test, to avoid repeating it.

For example :

namespace {
  class FooTest : public ::testing::Test {

  protected:
    Foo * pFoo_;

    FooTest() {
    }

    virtual ~FooTest() {
    }

    virtual void SetUp() {
      pFoo_ = new Foo();
    }

    virtual void TearDown() {
      delete pFoo_;
    }

  };

  TEST_F(FooTest, CanDoBar) {
      // You can assume that the code in SetUp has been executed
      //         pFoo_->bar(...)
      // The code in TearDown will be run after the end of this test
  }

  TEST_F(FooTest, CanDoBaz) {
     // The code from SetUp will have been executed *again*
     // pFoo_->baz(...)
      // The code in TearDown will be run *again* after the end of this test

  }

} // Namespace