1. 程式人生 > >Google開源C++單元測試框架Google Test系列(gtest)之- 事件機制

Google開源C++單元測試框架Google Test系列(gtest)之- 事件機制

gtest提供了多種事件機制,非常方便我們在案例之前或之後做一些操作。總結一下gtest的事件一共有3種:

  1. 全域性的,所有案例執行前後。
  2. TestSuite級別的,在某一批案例中第一個案例前,最後一個案例執行後
  3.  TestCase級別的,每個TestCase前後。

全域性事件

     要實現全域性事件,必須寫一個類,繼承testing::Environment類,實現裡面的SetUp和TearDown方法。

SetUp()方法在所有案例執行前執行

TearDown()方法在所有案例執行後執行

class FooEnvironment : public testing::Environment
{
public:
    virtual void SetUp()
    {
        std::cout << "Foo FooEnvironment SetUP" << std::endl;
    }
 
    virtual void TearDown()
    {
        std::cout << "Foo FooEnvironment TearDown" << std::endl;
    }
};

      當然,這樣還不夠,我們還需要告訴gtest新增這個全域性事件,我們需要在main函式中通過testing::AddGlobalTestEnvironment方法將事件掛進來,也就是說,我們可以寫很多個這樣的類,然後將他們的事件都掛上去。

int _tmain(int argc, _TCHAR* argv[])
{
    testing::AddGlobalTestEnvironment(new FooEnvironment);
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

TestSuite事件

      我們需要寫一個類,繼承testing::Test,然後實現兩個靜態方法  

      SetUpTestCase() 方法在第一個TestCase之前執行  

     TearDownTestCase() 方法在最後一個TestCase之後執行

class FooTest : public testing::Test {
 protected:
  static void SetUpTestCase() {
    shared_resource_ = new ;
  }
  static void TearDownTestCase() {
    delete shared_resource_;
    shared_resource_ = NULL;
  }
  // Some expensive resource shared by all tests.
  static T* shared_resource_;
};
在編寫測試案例時,我們需要使用TEST_F這個巨集,第一個引數必須是我們上面類的名字,代表一個TestSuite。
TEST_F(FooTest, Test1)
 {
    // you can refer to shared_resource here 
}
TEST_F(FooTest, Test2)
 {
    // you can refer to shared_resource here 
}

TestCase 事件

       TestCase事件是掛在每個案例執行前後的,實現方式和上面的幾乎一樣,不過需要實現的是SetUp方法和TearDown方法:

SetUp()方法在每個TestCase之前執行

TearDown()方法在每個TestCase之後執行

class FooCalcTest:public testing::Test
{
protected:
    virtual void SetUp()
    {
        m_foo.Init();
    }
    virtual void TearDown()
    {
        m_foo.Finalize();
    }
 
    FooCalc m_foo;
};
 
TEST_F(FooCalcTest, HandleNoneZeroInput)
{
    EXPECT_EQ(4, m_foo.Calc(12, 16));
}
 
TEST_F(FooCalcTest, HandleNoneZeroInput_Error)
{
    EXPECT_EQ(5, m_foo.Calc(12, 16));
}