三行代碼實現C語言單元測試框架?對,你沒有聽錯,三行代碼確實可以實現一個簡單的C語言的測試框架。不說廢話上代碼:
/* tcut.h: Tiny C Unit Test framework*/ #ifndef _TCUT_H #define _TCUT_H #define tcut_assert(what, test) do { if (!(test)) return what; } while (0) #define tcut_run_test(test) do { char *what = test(); nr_tests++; if (what) return what; } while (0) extern int nr_tests; #endif
測試代碼如下:
#include <stdio.h> #include "tcut.h" int nr_tests = 0; int foo = 7; int bar = 4; static char * test_foo() { tcut_assert("error, foo != 7", foo == 7); return 0; } static char * test_bar() { tcut_assert("error, bar != 5", bar == 5); return 0; } static char * all_tests() { tcut_run_test(test_foo); tcut_run_test(test_bar); return 0; } int main(int argc, char **argv) { char *result = all_tests(); if (result != 0) { printf("%s\n", result); } else { printf("ALL TESTS PASSED\n"); } printf("Tests run: %d\n", nr_tests); return result != 0; }
好了,C單元測試框架,就是這么簡單。
