三行代码实现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单元测试框架,就是这么简单。

原文地址:https://www.cnblogs.com/haippy/p/2653407.html