GTest是Google开发的跨平台而且开源的C++单元测试框架,很好很强大。
下载地址:https://code.google.com/p/googletest/ 。
关于GTest在Windows下使用,CoderZh给出了十分详尽的使用指南:
玩转Google开源C++单元测试框架Google Test系列
本文由如下部分组成:
下载下来,解压开,会发现有很多文件,这些是为了支持不同的平台和支持不同的构建方式。msvc文件用于微软Visual Studio中,xcode用于Mac Xcode ,codegrear用于Borland C++ builder,为避免混淆,在这里我简化为以下几个目录:
待测试的源码放入src目录下。
TrunQHexToFloat.h
#ifndef TRUN_Q_HEX_TO_FLOAT_H
#define TRUN_Q_HEX_TO_FLOAT_H
bool trunQHexToFloat(unsigned char src[],int len,float *Qval);
#endif
TrunQHexToFloat.c
#include
#include
#include
#include
bool trunQHexToFloat(unsigned char src[],int len,float *Qval)
{
if( len != 4 || Qval==NULL)
{
return false;
}
typedef union
{
unsigned char QvalHex[4];
float QvalFloat;
}QHexTof;
QHexTof data;
data.QvalHex[0] = src[0];
data.QvalHex[1] = src[1];
data.QvalHex[2] = src[2];
data.QvalHex[3] = src[3];
*Qval=data.QvalFloat;
return true;
}
测试例在testcase目录下
testQuTof.c
#include "gtest/gtest.h"
#include
#include "TrunQHexToFloat.h"
TEST(QuToFTest1, Demo)
{
float test;
unsigned char sample[]={0xab,0x5c,0x0b,0xbe} ;
int len = sizeof(sample)/sizeof(unsigned char);
EXPECT_TRUE(trunQHexToFloat(sample,len,&test));
}
TEST(QuToFTest2, Demo)
{
float test;
unsigned char sample[]={} ;
int len = sizeof(sample)/sizeof(unsigned char);
EXPECT_FALSE(trunQHexToFloat(sample,len,&test));
}
TEST(QuToFTest3, Demo)
{
float test;
unsigned char sample[]={0xac,0xab,0x5c,0x0b,0xbe} ;
int len = sizeof(sample)/sizeof(unsigned char);
EXPECT_FALSE(trunQHexToFloat(sample,len,&test));
}
TEST(QuToFTest4, Demo)
{
float test=NULL;
unsigned char sample[]={0xab,0x5c,0x0b,0xbe} ;
int len = sizeof(sample)/sizeof(unsigned char);
EXPECT_TRUE(trunQHexToFloat(sample,len,&test));
}
1 #include <gtest/gtest.h>
2
3 int main(int argc, char *argv[])
4 {
5
6 testing::InitGoogleTest(&argc, argv);
7 return RUN_ALL_TESTS();
8 }
在project目录下,新建CMakeLists.txt
PROJECT(unitTest)
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
SET(CMAKE_C_COMPILER "g++")
#设置路径
SET(GTEST_BASE_DIR ${CMAKE_CURRENT_LIST_DIR}/../gtest)
SET(MOCKCPP_BASE_DIR ${CMAKE_CURRENT_LIST_DIR}/../mockcpp)
SET(SOURCE_BASE_DIR ${CMAKE_CURRENT_LIST_DIR}/../src)
SET(TEST_CASE_DIR ${CMAKE_CURRENT_LIST_DIR}/../testcase)
INCLUDE_DIRECTORIES(
${GTEST_BASE_DIR}/include
${MOCKCPP_BASE_DIR}/include
${SOURCE_BASE_DIR}
)
#增加业务侧代码路径
FILE(GLOB_RECURSE SRC_PATH RELATIVE ${CMAKE_CURRENT_LIST_DIR} ${SOURCE_BASE_DIR}/*)
#增加测试用例代码
FILE(GLOB_RECURSE TESTCASE_PATH RELATIVE ${CMAKE_CURRENT_LIST_DIR} ${TEST_CASE_DIR}/*)
#增加主函数代码
FILE(GLOB_RECURSE MAIN_PATH RELATIVE ${CMAKE_CURRENT_LIST_DIR} ${TEST_CASE_DIR}/../main/*)
#追加SOURCEPATH
LIST(APPEND SOURCEPATH ${SRC_PATH})
LIST(APPEND SOURCEPATH ${TESTCASE_PATH})
LIST(APPEND SOURCEPATH ${MAIN_PATH})
#链接lib库路径
LINK_DIRECTORIES(${GTEST_BASE_DIR}/build)
LINK_DIRECTORIES(${MOCKCPP_BASE_DIR}/build/src)
ADD_EXECUTABLE(${PROJECT_NAME} ${SOURCEPATH})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} gtest mockcpp)
使用cmake生成MakeFile
cmake .
或者 cmake CMakeLists.txt
然后
make
生成可执行程序unitTest
运行
./unitTest
结果如下: