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

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


当前回答

使用的一种技术是使用c++ xUnit框架(和c++编译器)开发单元测试代码,同时将目标系统的源代码维护为C模块。

确保在交叉编译器下定期编译C源代码,如果可能的话自动使用单元测试。

其他回答

谷歌拥有优秀的测试框架。https://github.com/google/googletest/blob/master/googletest/docs/primer.md

是的,据我所知,它将与普通C一起工作,即不需要c++功能(可能需要c++编译器,不确定)。

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

CppUTest—强烈推荐用于单元测试C代码的框架。

书中提到的嵌入式C线程TDD中的示例是使用CppUTest编写的。

我们编写CHEAT(托管在GitHub上)是为了便于使用和移植。

它没有依赖关系,不需要安装或配置。 只需要一个头文件和一个测试用例。

#include <cheat.h>

CHEAT_TEST(mathematics_still_work,
    cheat_assert(2 + 2 == 4);
    cheat_assert_not(2 + 2 == 5);
)

测试编译成一个可执行文件,负责运行测试并报告测试结果。

$ gcc -I . tests.c
$ ./a.out
..
---
2 successful of 2 run
SUCCESS

它也有漂亮的颜色。

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