三行代碼實現C語言單元測試框架


三行代碼實現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單元測試框架,就是這么簡單。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM