玩转Google开源C++单元测试框架Google Test系列(gtest)之三 - 事件机制
一、前言
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宏,我們可以在案例之間共享一些通用方法,共享資源。使得我們的案例更加的簡潔,清晰。
總結
以上是生活随笔為你收集整理的玩转Google开源C++单元测试框架Google Test系列(gtest)之三 - 事件机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玩转Google开源C++单元测试框架G
- 下一篇: 玩转Google开源C++单元测试框架G