在前兩章中,我們已完成從環境搭建到流水線編譯的自動化配置。為了真正保障軟件質量、降低回歸風險,本章將聚焦測試自動化,涵蓋從最基礎的單元測試,到集成測試,再到硬件在環(Hardware-in-the-Loop, HIL)測試的全流程。通過腳本驅動、測試報告可視化和與 CI 平臺深度集成,實現“每次提交 → 自動測試 → 實時反饋”的閉環。
3.1 單元測試框架集成:CMock + Unity
3.1.1 為什么要做單元測試
-
隔離代碼邏輯:專注函數級或模塊級的輸入-輸出驗證,快速定位缺陷。
-
回歸保護:歷史 bug 修復后,新增測試用例能防止重現。
-
文檔化行為:測試代碼即使用示例,提升可維護性。
3.1.2 搭建 Unity 與 CMock
-
下載與項目結構
git clone https://github.com/ThrowTheSwitch/Unity.git tests/unity git clone https://github.com/ThrowTheSwitch/CMock.git tests/cmock
目錄示例:
├── src/ │ ├── foo.c │ └── foo.h ├── tests/ │ ├── unity/ │ ├── cmock/ │ └── test_foo.c └── Makefile
-
生成 Mock 代碼
在Makefile
中增加:CMOCK = ruby tests/cmock/lib/cmock.rb CMOCK_FLAGS = -o tests/mocks -x tests/cmock/lib -t tests/unity/src MOCK_FILES := $(patsubst src/%.h,tests/mocks/%_mock.c,$(wildcard src/*.h))tests/mocks/%_mock.c: src/%.h@mkdir -p tests/mocks$(CMOCK) $(CMOCK_FLAGS) -c $<test: $(MOCK_FILES) tests/test_foo.ccc -Isrc -Itests/unity/src -Itests/mocks \src/foo.c tests/mocks/foo_mock.c tests/test_foo.c