gtest中的事件机制

来源:互联网 发布:突破公司网络限制 编辑:程序博客网 时间:2024/05/02 00:53


gtest中提供了三种事件机制,分别是

1. 全局的事件,所有案例执行前后;

2. TestSuite级别的事件,在每个TestSuite执行的前后;

3. TestCase级别的事件,在每个TestCase执行的前后。


对应2,3这两种事件机制,编写测试案例时,需要用到TEST_F宏。


一、全局事件


要实现全局事件,必须写一个类,继承testing::Environment 类,并实现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;
    }
};


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

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

二、TestSuite事件

对于TestSuite级别的事件,我们需要写一个类,继承testing::Test,并实现两个静态方法SetUpTestCase和TearDownTestCase。

1. SetUpTestCase方法在每个TestSuite的的第一个TestCase之前运行。

2. TearDownTestCase方法在每个TestSuite的最后一个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(1216));
}

TEST_F(FooCalcTest, HandleNoneZeroInput_Error)
{
    EXPECT_EQ(
5, m_foo.Calc(1216));
}


0 0
原创粉丝点击