`
tibaloga
  • 浏览: 870538 次
文章分类
社区版块
存档分类
最新评论

【转】玩转Google开源C++单元测试框架Google Test系列(gtest)之三 - 事件机制

 
阅读更多

原文地址:http://www.cnblogs.com/coderzh/archive/2009/04/06/1430396.html

一、前言

gtest提供了多种事件机制,非常方便我们在案例之前或之后做一些操作。总结一下gtest的事件一共有3种:

1. 全局的,所有案例执行前后。

2. TestSuite级别的,在某一批案例中第一个案例前,最后一个案例执行后。

3. TestCae级别的,每个TestCase前后。

二、全局事件

要实现全局事件,必须写一个类,继承testing::Environment类,实现里面的SetUp和TearDown方法。

1. SetUp()方法在所有案例执行前执行

2. TearDown()方法在所有案例执行后执行

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->class FooEnvironment: public testing::Environment
{
public :
virtual void SetUp()
{
std::cout
<< " FooFooEnvironmentSetUP " << std::endl;
}
virtual void TearDown()
{
std::cout
<< " FooFooEnvironmentTearDown " << std::endl;
}
};

当然,这样还不够,我们还需要告诉gtest添加这个全局事件,我们需要在main函数中通过testing::AddGlobalTestEnvironment方法将事件挂进来,也就是说,我们可以写很多个这样的类,然后将他们的事件都挂上去。

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->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之后执行

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->class FooTest: public testing::Test{
protected :
static void SetUpTestCase(){
shared_resource_
= new ;
}
static void TearDownTestCase(){
deleteshared_resource_;
shared_resource_
= NULL;
}
// Someexpensiveresourcesharedbyalltests.
static T * shared_resource_;
};
在编写测试案例时,我们需要使用TEST_F这个宏,第一个参数必须是我们上面类的名字,代表一个TestSuite。

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->TEST_F(FooTest,Test1)
{
// youcanrefertoshared_resourcehere
}
TEST_F(FooTest,Test2)
{
// youcanrefertoshared_resourcehere
}

四、TestCase事件

TestCase事件是挂在每个案例执行前后的,实现方式和上面的几乎一样,不过需要实现的是SetUp方法和TearDown方法:

1. SetUp()方法在每个TestCase之前执行

2. TearDown()方法在每个TestCase之后执行

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->class FooCalcTest: public testing::Test
{
protected :
virtual void SetUp()
{
m_foo.Init();
}
virtual void TearDown()
{
m_foo.Finalize();
}

FooCalcm_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宏,我们可以在案例之间共享一些通用方法,共享资源。使得我们的案例更加的简洁,清晰。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics