使用C进行依赖注入。如何运行所有测试?

使用C进行依赖注入。如何运行所有测试?,c,testing,dependency-injection,C,Testing,Dependency Injection,所以我用[MinUnit][1]来运行我的C测试 这是图书馆: /* file: minunit.h */ #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)

所以我用[MinUnit][1]来运行我的C测试

这是图书馆:

 /* file: minunit.h */
 #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;
这是我如何使用它的一个例子

#include "minunit.h"
#include "function_under_test_source.c"
static char *test_ac1() {
    mu_assert("max char, should broke, it didn't",
              function_under_test() == 1);
    return 0;
}
static char *all_tests() {
    mu_run_test(test_ac1);
    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;
}
每次都要写一点锅炉板,但它符合我的目的

现在,为了能够从生产代码中抽象测试,我想使用依赖注入。例如,如果我想测试一个使用
getchar
的函数,我要做的是:

int get_string(char s[], int maxChar, int (*getchar)()) {
因此,我将指针传递给实际函数,然后在测试中模拟它,如下所示:

const char *mock_getchar_data_ptr;

char        mock_getchar() {
    return *mock_getchar_data_ptr++;
}
然后我在测试中使用它,如下所示:

static char *test_ac2() {
    char text[100];
    mock_getchar_data_ptr = "\nhello!\n"; // the initial \n is there because I'm using scanf on production code (main.c)
    get_string(text, 100, mock_getchar);
    mu_assert("text is hello", strcmp(text, "hello!") == 0);
    return 0;
}
这是可行的,但问题是我正在为每个单元测试创建一个C文件,然后我正在编译每个测试文件,并运行编译后的版本来测试它是否可行

我当然可以创建一个makefile,但我想知道是否有一个更自动的测试编排

谢谢 [1] :