参考网址
https://mp.weixin.qq.com/s/CklfQPoyvJCKv8ohu-oqOw
例程
1 2 3 4 5
| #define mu_assert(message, test) do { if (!(test)) return message; } while (0) #define mu_run_test(test) do { char *message = test(); tests_run++; \ if (message) return message; } while (0) extern int tests_run;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <stdio.h> #include "minunit.h" int tests_run = 0; int foo = 7; int bar = 4; static char * test_foo() { mu_assert("error, foo != 7", foo == 7); return 0; } static char * test_bar() { mu_assert("error, bar != 5", bar == 5); return 0; } static char * all_tests() { mu_run_test(test_foo); mu_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", tests_run); return result != 0; }
|
结果
1 2
| error, bar != 5 Tests run: 2
|
参考之后自己写的cc版本的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include<iostream>
class MuTest { public: static int tests_run; static char *run_test(char *(*test)()) { char *message = test(); tests_run++; if (message) return message; return 0; }
static char *assert_true(bool test, char *message) { if (!test) return message; return 0; } };
int MuTest::tests_run = 0;
char *test_fail() { return MuTest::assert_true(false, (char *)"fail"); }
char *test_pass() { return MuTest::assert_true(true, (char *)"pass"); }
char *all_tests() { char *message = 0; message = MuTest::run_test(test_fail); if (message) return message; message = MuTest::run_test(test_pass); if (message) return message; return 0; }
int main() { char *message = all_tests(); if (message) std::cout << message << std::endl; else std::cout << "ALL TESTS PASSED" << std::endl; std::cout << "Tests run: " << MuTest::tests_run << std::endl; return 0; }
|
结果