CPPUTest 虽然名称上看起来是 C++ 的单元测试框架, 其实它也是支持测试 C 代码的.
  本文主要介绍用CPPUTest来测试 C 代码. (C++没用过, 平时主要用的是C) C++相关的内容都省略了.
  本文基于 debian v7.6 x86_64.
  1. CPPUTest 安装
  现在各个Linux的发行版的源都有丰富的软件资源, 而且安装方便.
  但是如果想要在第一时间使用新版本的开源软件, 还是得从源码安装.
  debian系统为了追求稳定性, apt源中的软件一般都比较旧. 所以本文中的例子是基于新源码的CPPUTest.
  1.1 apt-get 安装
  $ sudo apt-get install cpputest
  1.2 源码安装
  1. 下载源码, 官网: http://cpputest.github.io/
  2. 编译源码
  $ tar zxvf cpputest-3.6.tar.gz
  $ cd cpputest-3.6/
  $ ./configure
  $ make
  后我没有实际安装, 而是直接使用编译出的二进制。
  2. CPPUTest 介绍
  2.1 构造待测试代码 (C语言)
/* file: sample.h */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student
{
char* name;
int score;
};
void ret_void(void);
int ret_int(int, int);
double ret_double(double, double);
char* ret_pchar(char*, char*);
struct Student* init_student(struct Student* s, char* name, int score);
/* file: sample.c */
#include "sample.h"
#ifndef CPPUTEST
int main(int argc, char *argv[])
{
char* pa;
char* pb;
pa = (char*) malloc(sizeof(char) * 80);
pb = (char*) malloc(sizeof(char) * 20);
strcpy(pa, "abcdefg");
strcpy(pb, "hijklmn");
printf ("Sample Start...... ");
ret_void();
printf ("ret_int: %d ", ret_int(100, 10));
printf ("ret_double: %.2f ", ret_double(100.0, 10.0));
printf ("ret_pchar: %s ", ret_pchar(pa, pb));
struct Student* s = (struct Student*) malloc(sizeof(struct Student));
s->name = (char*) malloc(sizeof(char) * 80);
init_student(s, "test cpputest", 100);
printf ("init_Student: name=%s, score=%d ", s->name, s->score);
printf ("Sample End  ...... ");
free(pa);
free(pb);
free(s->name);
free(s);
return 0;
}
#endif
void ret_void()
{
printf ("Hello CPPUTest! ");
}
/* ia + ib */
int ret_int(int ia, int ib)
{
return ia + ib;
}
/* da / db */
double ret_double(double da, double db)
{
return da / db;
}
/* pa = pa + pb */
char* ret_pchar(char* pa, char* pb)
{
return strcat(pa, pb);
}
/* s->name = name, s->score = score */
void init_student(struct Student* s, char* name, int score)
{
strcpy(s->name, name);
s->score = score;
}