2014-09-25 291 views
3

我目前在學習單元測試google mock谷歌模擬中virtual void SetUp()virtual void TearDown()的常用用法是什麼?有代碼的示例場景會很好。提前致謝。單元測試C++ setup()和teardown()

+3

的*模擬*沒有這樣的方法。這些是* test fixture *上的方法,它是Google Test的一個組件,而不是Google Mock。通常,您可能確實需要這些方法,因爲構造函數和析構函數將用於相同的目的。請參閱[文檔](https://code.google.com/p/googletest/wiki/V1_7_Primer#Test_Fixtures :_Using_the_Same_Data_Configuration_for_Multiple_Te)和[FAQ](https://code.google.com/p/googletest/wiki/)。 V1_7_FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t)。 – 2014-10-12 15:58:38

+1

谷歌模擬中沒有這樣的功能,它來自谷歌測試 – ratzip 2015-09-08 07:09:36

回答

4

這是爲了在每個測試的開始和結束時對要執行的代碼進行分解,以避免重複它。

例如:

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 
+0

如有必要,編寫一個默認構造函數或SetUp()函數爲每個測試準備對象。一個常見的錯誤是將SetUp()作爲Setup()與一個小U拼寫 - 不要讓這發生在你身上。 https://github.com/google/googletest/blob/master/googletest/docs/Primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests#3 – 2017-08-25 13:12:03