gtest使用示例

gtest简单应用(本文参考自CoderZHu的技术博客)

main中启动gtest的方法

#include <gtest/gtest.h>

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);

    auto result =  RUN_ALL_TESTS();
#ifdef _MSC_VER
   system("pause");
#endif
   return result;
}

简单的测试用例与常见断言

  • 示例代码
#include <gtest/gtest.h>

TEST(FooTest, HandleNoneZeroInput)
{
    EXPECT_EQ(2, Foo(4, 10));
    EXPECT_EQ(6, Foo(30, 18));
}
  • 常见断言类型
    * 布尔值检查
    * 数值型数据检查
    * 字符串检查
    * 异常检查
    * Predicate Assertions
    * 浮点型检查
    * 其他

gtest的事件参考

所谓的事件其实就是准备与清理某段测试代码所需的环境

全局事件
  • 要实现全局事件,必须写一个类,继承testing::Environment类,实现里面的SetUp和TearDown方法,然后告诉gtest添加这个全局事件,我们需要在main函数中通过testing::AddGlobalTestEnvironment方法将事件挂进来。
    * SetUp()方法在所有案例执行前执行
    * TearDown()方法在所有案例执行后执行
    * 使用testing::AddGlobalTestEnvironment添加全局事件
  • 示例代码
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;
    }
};

int main(int argc, _TCHAR* argv[])
{
    testing::AddGlobalTestEnvironment(new FooEnvironment);
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
TestSuite事件(一个测试用例集合的前后)
  • 我们需要写一个类,继承testing::Test,然后实现两个静态方法
    * SetUpTestCase() 方法在第一个TestCase之前执行
    * TearDownTestCase() 方法在最后一个TestCase之后执行
    * 使用TEST_F这个宏,第一个参数必须是上面类的名字,代表一个TestSuite
  • 示例代码
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事件(每个测试用例的前后)
  • 实现方法与上面类似,只不过需要实现的是SetUp方法和TearDown方法
    * SetUp()方法在每个TestCase之前执行
    * 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的死亡测试能做到在一个安全的环境下执行崩溃的测试案例,同时又对崩溃结果进行验证。

运行参数

posted @ 2017-08-25 11:41  jiahu  阅读(1099)  评论(0编辑  收藏  举报