GoogleTest
vs2017已经继承了GTest
参考资料
参考资料
尽量使用正式发布版本,需要使用git brach -a
命令来查看正是版本的分支,再通过git checkout
命令来
不然需要在主目录下的CMakeLists.txt文件下添加
add_definitions(-std=c++11)
或者set(CMAKE_CXX_FLAGS "-std=c++0x")
ASSERT_*系列的断言,当检查点失败时,退出当前函数
EXPECT_*系列的断言,当检查点失败时,继续往下执行
// 布尔值检查
ASSERT_TRUE(condition);
EXPECT_TRUE(condition);
ASSERT_FALSE(condition);
EXPECT_FALSE(condition);
// 数值型数据检查
ASSERT_EQ(expected,actual);
ASSERT_NE(val1, val2);
ASSERT_LT(val1, val2);
ASSERT_LE(val1, val2);
ASSERT_GT(val1, val2);
ASSERT_GE(val1, val2);
// 字符串检查
ASSERT_STREQ(expected_str,actual_str);
ASSERT_STRNE(expected_str,actual_str);
ASSERT_STRCASEEQ(expected_str,actual_str); // 忽略大小写
ASSERT_STRCASENE(str1,str2); // 忽略大小写
// 显示返回成功或失败
SUCCEED(); // 直接返回成功
FALL();
ADD_FALURE();
// 异常检查
ASSERT_THROW(statement, exception_type); // statement是否抛出给定类型的异常
ASSERT_ANY_THROW(statement); // statement是否抛出异常
ASSERT_NO_THROW(statement); // statement不抛出任何异常
// 浮点型检查
ASSERT_FLOAT_EQ(expected,actual);
ASSERT_DOUBLE_EQ(expected,actual);
事件机制
参考资料
参考资料(*)
参考资料
编写在.cc文件中,需要在上一级目录的CMakeLists.txt文件中该位置处添加如下信息。若.cc文件中有main函数,则不需要添加gtest_main,但需要添加gtest。若.cc文件中没有main函数,则需要添加gtest_main,而不必添加gtest。
- TestCase级别
- TestSuite级别
#include <iostream>
#include <map>
#include "gtest/gtest.h"
using std::cout;
using std::endl;
using std::make_pair;
using std::map;
class TestMap : public testing::Test {
public:
static void SetUpTestCase() { cout << "SetUpTestCase()" << endl; }
static void TearDownTestCase() { cout << "TearDownTestCase()" << endl; }
void SetUp() {
cout << "SetUp()" << endl;
mp.insert(make_pair(1, 1));
mp.insert(make_pair(2, 1));
mp.insert(make_pair(3, 1));
mp.insert(make_pair(4, 1));
}
void TearDown() {
mp.clear();
cout << "TearDown()" << endl;
}
map<int, int> mp;
};
TEST_F(TestMap, Find) {
map<int, int>::iterator it = mp.find(2);
ASSERT_NE(it, mp.end());
}
TEST_F(TestMap, Size) { ASSERT_EQ(4, mp.size()); }
- 全局事件
总结:
testSuite需要编写一个类继承testing::Test,然后实现两个静态方法(protected):SetUpTestCase()和TearDownTestCase()
testCase同样类继承testing::Test,然后实现两个虚方法(protected):SetUp()和TearDown()
SetUpTestCase()方法只在第一个TestCase之前执行
TearDownTestCase()方法只在最后一个TestCase之后执行
SetUp方法在每个TestCase之前执行
TearDown()方法在每个TestCase之后执行
编写测试案例时要使用TEST_F()宏
运行参数
- –gtest_list_test
列出所有测试名字 - –gtest_filter=POSTIVE_PATTERNS
运行与正则表达式匹配的测试,没有 - –gtest_also_run_disabled_tests
运行所有禁用的测试
在测试案例名称或测试名称中添加DISABLED前缀,可以将其设置为无效的测试案例