gtest的使用
代码
#include <iostream>
using namespace std;
/**
* 全局环境事件,在主函数中 testing::AddGlobalTestEnvironment(new envirment()) 来使用
* 在所有测试用例的前后调用。
*
*/
class envirment : public testing::Environment
{
public:
virtual void SetUp()
{
cout << "environment setup" << endl;
}
virtual void TearDown()
{
cout << "environment teardown" << endl;
}
};
/// 测试宏一
TEST(tt, null)
{
string input = "234";
EXPECT_EQ(input, "234");
}
int func(int data[10])
{
/// pass
return data[9];
}
int func2(int data[10])
{
/// pass
return data[9];
}
/**
* 测试宏二:TEST_F
* 用于在多个测试用例下需要使用相同的数据的情况下
*
* 需要实现一个类,继承 testing::Test,类实现虚函数SetUp和TearDown,以及静态方法SetUpTestCase和TearDownTestCase
* 其中SetUp和TearDown分别在每个测试用例前后调用
* SetUpTestCase和TearDownTestCase在所有测试用例前后调用
*
* */
class TestCase : public testing::Test
{
public:
/// 每个用例前都调用一次
virtual void SetUp()
{
cout << "setup" << endl;
for (int i = 0; i < 10; i++)
{
data[i] = i * i;
}
data[9] = 1500;
}
virtual void TearDown()
{
cout << "teardown" << endl;
data[9] = 0;
}
/// 所有用例前调用一次
static void SetUpTestCase()
{
cout << "setup test case" << endl;
}
static void TearDownTestCase()
{
cout << "TearDown test case" << endl;
}
int data[10];
};
/// 测试用例一
TEST_F(TestCase, hello)
{
cout << "in test f1 " << data[9] << endl;
int ret = func(data);
EXPECT_EQ(ret, 1500);
}
/// 测试用例二
TEST_F(TestCase, helo2)
{
cout << "in test f2 " << data[9] << endl;
int ret = func2(data);
EXPECT_EQ(ret, 1500);
}
/**
* 测试宏三:TEST_P
* step1:定义参数 呼叫参数类(结构体)
* step2:定义呼叫类,继承testing::TestWithParam<type> type为呼叫类类型
* step3:使用INSTANTIATE_TEST_CASE_P 进行多参数设置
* step4:用TEST_P进行用例测试
*
*/
/// step1
struct param
{
int num1;
int num2;
};
/// step2
class testPrm : public testing::TestWithParam<int>
{
};
/// step3
INSTANTIATE_TEST_CASE_P(T, testPrm, ::testing::Values(1, 2, 3));
INSTANTIATE_TEST_CASE_P(T2, testPrm, ::testing::Values(4));
/// step4
TEST_P(testPrm, TT)
{
int p = GetParam();
cout << p << std::endl;
}
int main(int argc, char **argv)
{
/// init gtest
::testing::InitGoogleTest(&argc, argv);
/// init global env
::testing::AddGlobalTestEnvironment(new envirment());
/// run all TEST case
return RUN_ALL_TESTS();
}
编译(cmakelists.txt)
PROJECT(gtest)
set(CMAKE_CXX_FLAGS "--std=c++11")
find_package(GTest)
include_directories(${GTEST_INCLUDE_DIRS})
ADD_EXECUTABLE(main test/test.cpp)
SET(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR})
TARGET_LINK_LIBRARIES(main ${GTEST_LIBRARIES} pthread)