gtest是google的C++测试框架,很好用。
我借鉴了http://www.cnblogs.com/coderzh/archive/2009/04/06/1426755.html里面的教程来使用gtest
google test的单元测试仅需要TEST()和TEST_F()两个宏,
TEST:定义一次测试
第一个参数是测试用例名,第二个参数是测试名
通过RUN_ALL_TESTS()来运行它们,如果所有测试成功,该函数返回0,否则会返回1.
你不能忽略掉RUN_ALL_TESTS()的返回值,否则gcc会报一个编译错误。这样设计的理由是自动化测试服务会根据测试退出返回码来决定一个测试是否通过,而不是根据其stdout/stderr输出;因此你的main()函数必须返回RUN_ALL_TESTS()的值。而且,你应该只调用RUN_ALL_TESTS()一次。多次调用该函数会与Google Test的一些高阶特性(如线程安全死亡测试thread-safe death tests)冲突,因而是不被支持的。
testing::InitGoogleTest() 函数负责解析命令行传入的Google Test标志,必须在调用RUN_ALL_TESTS()之前调用该函数,否则就无法正确地初始化标示。
#include "../include/mysql_connection_pool.h"
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <thread>
#include <gtest/gtest.h>
using std::cout;
using std::endl;
using std::thread;
const char* handler(MysqlPool* p_mypool, const char* sql)
{
// 从数据库连接池当中取出一个可用的连接
MysqlObj* conn = p_mypool->getConnection();
if(!conn){
cout << "getConnection NULL pointer" << endl;
exit(-1);
}
QueryResult queryResult;
conn->ExecuteSql(sql, queryResult);
p_mypool->releaseConnection(conn);
for(int i=0;i<queryResult.getRowCount();i++)
{
for(int j=0;j<queryResult.getColumnCount();j++)
{
cout << queryResult.getElement(i,j) << " ";
}
cout << endl;
}
return "hello";
}
TEST(handlerTest, Test1)
{
MysqlPool mypool;
EXPECT_STREQ("hello", handler(&mypool, "select * from student"));
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}