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

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


当前回答

我不使用框架,我只是使用自动工具“检查”目标支持。实现一个“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

其他回答

您可能还想看看libtap,这是一个输出任何测试协议(TAP)的C测试框架,因此可以很好地与用于该技术的各种工具集成。它主要用于动态语言领域,但它易于使用,并且变得非常流行。

一个例子:

#include <tap.h>

int main () {
    plan(5);

    ok(3 == 3);
    is("fnord", "eek", "two different strings not that way?");
    ok(3 <= 8732, "%d <= %d", 3, 8732);
    like("fnord", "f(yes|no)r*[a-f]$");
    cmp_ok(3, ">=", 10);

    done_testing();
}

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的测试套件

我很惊讶没有人提到卡特(http://cutter.sourceforge.net/) 你可以测试C和c++,它与autotools无缝集成,并且有一个非常好的教程。

如果你熟悉JUnit,那么我推荐CppUnit。 http://cppunit.sourceforge.net/cppunit-wiki

这是假设你有c++编译器来做单元测试。如果没有,那么我必须同意亚当·罗森菲尔德的观点,支票就是你想要的。

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

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