C++单元测试 之 gtest -- 组合数计算.

时间:2023-03-08 16:46:29

本文将介绍如何使用gtest进行单元测试.

gtest是google单元测试框架.使用非常方便.

首先,下载gtest (有些google项目包含gtest,如 protobuf),复制目录即可使用.

http://code.google.com/p/googletest/

如果被墙,就百度搜下,很多.

解压 gtest.zip, 得到gtest.1.x.x目录.

export GTEST_HOME=该目录

编译:
cd $GTEST_HOME/make
make

运行示例程序, 熟悉 gtest风格
./sample1_unittes

编译后还会得到一个 gtest_main.a 的静态库.
ln -s gtest_main.a libgtest.a
软链接以便符合 gcc 库引用规范.

按 sample1_unittes.cc 写好自己的测试代码(test.cpp)后,就可以开始编译

g++ -I$GTEST_HOME/include -L$GTEST_HOME/make -lgtest test.cpp -o test.exe
生成测试程序 test.exe

组合数计算代码 combination.cpp:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "combination.h" long combination(long base,long select) {
long res=;
if(base<select || base <= ) return ;
if(base==select) return ;
if(select >= base - select) {
res=arrangement(select+,base) / arrangement (,base - select);
}
else {
res=arrangement(base-select+,base) / arrangement (,select);
}
return res;
} long arrangement(long start,long end) {
if( start <= || start > end) {
return ;
}
long res=start;
for(long i=start+;i<=end;i++) {
res*=i;
}
return res;
}

头文件combination.h:

long combination(long base,long select);
long arrangement(long start,long end);

测试代码 gtest_combination.cpp

#include <limits.h>
#include "combination.h"
#include <gtest/gtest.h> TEST(arrangement, all) {
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(, arrangement(,));
EXPECT_EQ(**, arrangement(,)); } TEST(combination, all) {
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(-,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
EXPECT_EQ(, combination(,));
}

Makefile:

TEST=gtest_combination
TESTOBJ=$(TEST).o
TAROBJ=combination.o

all: $(TEST)

$(TEST): $(TESTOBJ) $(TAROBJ)
g++ -I$(GTEST_HOME)/include -L$(GTEST_HOME)/make -lgtest $^ -o $@

%.o: %.cpp
g++ -c -I$(GTEST_HOME)/include -g -o $@ $<

编译及测试:

$make

$gtest_combination

输出结果:

Running main() from gtest_main.cc
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from arrangement
[ RUN ] arrangement.all
[ OK ] arrangement.all (0 ms)
[----------] 1 test from arrangement (0 ms total)

[----------] 1 test from combination
[ RUN ] combination.all
[ OK ] combination.all (0 ms)
[----------] 1 test from combination (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (6 ms total)
[ PASSED ] 2 tests.