簡(jiǎn)介
googletest提供了多種事件機(jī)制:
- 全局的,所有案例執(zhí)行前后。
- TestSuite級(jí)別的,在某一批案例中第一個(gè)案例前,最后一個(gè)案例執(zhí)行后。
- TestCase級(jí)別的,每個(gè)TestCase前后。
全局事件
要實(shí)現(xiàn)全局事件,必須寫一個(gè)類,繼承testing::Environment類,實(shí)現(xiàn)里面的SetUp和TearDown方法。
SetUp()方法在所有案例執(zhí)行前執(zhí)行
TearDown()方法在所有案例執(zhí)行后執(zhí)行
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;
}
}
添加這個(gè)全局事件,我們需要在main函數(shù)中通過(guò)testing::AddGlobalTestEnvironment方法將事件掛進(jìn)來(lái),也就是說(shuō),我們可以寫很多個(gè)這樣的類,然后將他們的事件都掛上去。
int _tmain(int argc, _TCHAR* argv[])
{
testing::AddGlobalTestEnvironment(new FooEnvironment);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
TestSuite事件
我們需要寫一個(gè)類,繼承testing::Test,然后實(shí)現(xiàn)兩個(gè)靜態(tài)方法
SetUpTestCase() 方法在第一個(gè)TestCase之前執(zhí)行
TearDownTestCase() 方法在最后一個(gè)TestCase之后執(zhí)行</pre>
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(FooTest, Test1)
{
//you can refer to shared_resource here }
TEST_F(FooTest, Test2)
{
//you can refer to shared_resource here }
TestCase事件
TestCase事件是掛在每個(gè)案例執(zhí)行前后的,實(shí)現(xiàn)方式和上面的幾乎一樣,不過(guò)需要實(shí)現(xiàn)的是SetUp方法和TearDown方法:
- SetUp()方法在每個(gè)TestCase之前執(zhí)行
- TearDown()方法在每個(gè)TestCase之后執(zhí)行
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));
}
文章參考:https://www.cnblogs.com/coderzh/archive/2009/04/06/1430396.html