一、前言
gtest提供了多種事件機制,非常方便我們在案例之前或之後做一些操作。總結一下gtest的事件一共有3種:
1. 全域的,所有案例執行前後。
2. TestSuite層級的,在某一批案例中第一個案例前,最後一個案例執行後。
3. TestCase層級的,每個TestCase前後。
二、全域事件
要實現全域事件,必須寫一個類,繼承testing::Environment類,實現裡面的SetUp和TearDown方法。
1. SetUp()方法在所有案例執行前執行
2. 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,然後實現兩個靜態方法
1. SetUpTestCase() 方法在第一個TestCase之前執行
2. 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方法:
1. SetUp()方法在每個TestCase之前執行
2. 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));
}
五、總結
gtest提供的這三種事件機制還是非常的簡單和靈活的。同時,通過繼承Test類,使用TEST_F宏,我們可以在案例之間共用一些通用方法,共用資源。使得我們的案例更加的簡潔,清晰。
系列連結:
1.玩轉Google開源C++單元測試架構Google Test系列(gtest)之一 - 初識gtest
2.玩轉Google開源C++單元測試架構Google Test系列(gtest)之二 - 斷言
3.玩轉Google開源C++單元測試架構Google Test系列(gtest)之三 - 事件機制
4.玩轉Google開源C++單元測試架構Google Test系列(gtest)之四 - 參數化
5.玩轉Google開源C++單元測試架構Google Test系列(gtest)之五 - 死亡測試
6.玩轉Google開源C++單元測試架構Google Test系列(gtest)之六 - 運行參數
7.玩轉Google開源C++單元測試架構Google Test系列(gtest)之七 - 深入解析gtest
8.玩轉Google開源C++單元測試架構Google Test系列(gtest)之八 - 打造自己的單元測試架構