今年夏天,我开发了一个用纯c语言编写的嵌入式系统。这是我所在公司接管的一个现有项目。我已经非常习惯使用JUnit在Java中编写单元测试,但不知道为现有代码(需要重构)和添加到系统中的新代码编写单元测试的最佳方法是什么。

有什么项目可以让单元测试纯C代码像使用JUnit测试Java代码一样简单吗?任何特别适用于嵌入式开发(交叉编译到arm-linux平台)的见解都将非常感谢。


当前回答

首先,看看这里:http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C

我的公司有一个客户使用的C库。我们使用CxxTest(一个c++单元测试库)来测试代码。CppUnit也可以工作。如果你被C卡住了,我推荐RCUNIT(但CUnit也很好)。

其他回答

我编写Libcut只是出于对现有C单元测试库的不满。它具有原语的自动类型字符串(不需要test_eq_int, test_eq_long, test_eq_short,等等…)对于原语和字符串只有两个不同的集合),并且由一个头文件组成。这里有一个简短的例子:

#include <libcut.h>

LIBCUT_TEST(test_abc) {
    LIBCUT_TEST_EQ(1, 1);
    LIBCUT_TEST_NE(1, 0);
    LIBCUT_TEST_STREQ("abc", "abc");
    LIBCUT_TEST_STRNE("abc", "def");
}

LIBCUT_MAIN(test_abc);

不过,它只对C11有效。

cmock是最近推出的一个项目,由一个非常简单的C库组成,用于编写单元测试。

如果您的目标是Win32平台或NT内核模式,您应该看看cfix。

API完整性检查器- C/ c++库的测试框架:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files. The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

例子:

fontconfig 2.8.0测试套件 FreeType 2.4.8的测试套件

我不使用框架,我只是使用自动工具“检查”目标支持。实现一个“main”并使用assert。

我的测试目录Makefile.am(s)看起来像这样:

check_PROGRAMS = test_oe_amqp

test_oe_amqp_SOURCES = test_oe_amqp.c
test_oe_amqp_LDADD = -L$(top_builddir)/components/common -loecommon
test_oe_amqp_CFLAGS = -I$(top_srcdir)/components/common -static

TESTS = test_oe_amqp