Unity:专为嵌入式设计的 C 单元测试框架
🔗Unity 官方网站|🔗GitHub 项目
✅ 特点
-
轻量级实现:核心仅由一个
.c
文件和两个头文件组成 -
无依赖:不依赖标准库以外的组件,适合裸机环境
-
丰富断言:支持整数、浮点、字符串、数组、位操作等多种断言
-
跨平台:兼容 GCC、IAR、Clang、Green Hills、Microchip 等嵌入式编译器
-
易集成:可与 Makefile、CMake、PlatformIO 等构建系统配合使用
📦 资源占用
-
内存占用:极低,仅几 KB(取决于编译器优化和使用的断言数量)
-
代码体积:核心代码 < 20KB,适合 8-bit MCU
🛠 示例断言
下面是一步步的详细指南,适合初学者:
🧰 第一步:准备环境
确保你已经在 WSL 中安装了以下工具:
bash
sudo apt update
sudo apt install build-essential git
📦 第二步:下载 Unity 框架
Unity 是由ThrowTheSwitch.org 提供的开源项目,你可以通过 Git 克隆它:
bash
git clone https://github.com/ThrowTheSwitch/Unity.git
你也可以只复制 src/unity.c
和 src/unity.h
到你的项目中,Unity 的核心就是这两个文件。
🗂️ 第三步:创建你的测试项目结构
推荐的项目结构如下:
my_project/
├── src/ # 你的源代码
│ └── calculator.c
├── test/ # 测试代码
│ └── test_calculator.c
├── unity/ # Unity 框架代码
│ └── unity.c, unity.h
└── Makefile # 构建脚本
🧪 第四步:编写测试代码
示例 test/test_calculator.c
:
c
#include "unity.h"
#include "calculator.h"
void setUp(void) {} // 每个测试前调用
void tearDown(void) {} // 每个测试后调用
void test_Addition(void) {
TEST_ASSERT_EQUAL_INT(5, add(2, 3));
}
void test_Subtraction(void) {
TEST_ASSERT_EQUAL_INT(1, subtract(3, 2));
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_Addition);
RUN_TEST(test_Subtraction);
return UNITY_END();
}
🛠️ 第五步:编写 Makefile
示例 Makefile
:
makefile
CC = gcc
CFLAGS = -Iunity -Isrc -Itest
SRC = src/calculator.c
TEST = test/test_calculator.c
UNITY = unity/unity.c
TARGET = test_runner
all:
$(CC) $(CFLAGS) $(SRC) $(TEST) $(UNITY) -o $(TARGET)
./$(TARGET)
clean:
rm -f $(TARGET)
🚀 第六步:运行测试
在项目根目录下运行:
bash
make
你将看到类似输出:
test/test_calculator.c:10:test_Addition:PASS
test/test_calculator.c:14:test_Subtraction:PASS
-----------------------
2 Tests 0 Failures 0 Ignored
OK