Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 546
user2785929 Avatar asked Sep 25 '14 04:09

user2785929


People also ask

What is the use of setup () and tearDown ()?

Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown class method on XCTestCase .

What is setup and tearDown in Gtest?

For each test defined with TEST_F() , googletest will create a fresh test fixture at runtime, immediately initialize it via SetUp() , run the test, clean up by calling TearDown() , and then delete the test fixture.

What does the tearDown () function do?

tearDown()Provides an opportunity to perform cleanup after each test method in a test case ends.

Where will you use setup () and tearDown () methods and make it run once for all the tests in the class?

Discussion. As outlined in Recipe 4.6, JUnit calls setUp( ) before each test, and tearDown( ) after each test. In some cases you might want to call a special setup method once before a series of tests, and then call a teardown method once after all tests are complete.


1 Answers

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
like image 184
phtrivier Avatar answered Oct 05 '22 01:10

phtrivier