unit testing运行配置

我需要一些帮助来启动和运行cmockaunit testing框架。 我的设置是:

src / math / addition / add.c(+ add.h)

int add(int a, int b) {return a + b;} 

src / math / subtraction / sub.c(+ sub.h)

 int sub(int a, int b) {return a - b;} 

Makefile文件

 VPATH := src src/math src/math/addition CFLAGS += -Isrc -Isrc/math -Isrc/math/addition all: libMath clean libMath: add.o sub.o ar rcs bin/libMath add.o sub.o clean: rm -rf *.o %.o: %.c %.h 

unit testing

测试/数学/添加/ add_test.c

 #include "../src/math/addition/add.h" void test_add() { assert(add(4, 5), 9); } 

测试/数学/减/ sub_test.c

 #include "../src/math/subtraction/sub.h" void test_sub() { assert(sub(9, 5), 4); } 

test / math / addition / add_test.c (来自cmocka.org )

 #include  #include  #include  #include  /* A test case that does nothing and succeeds. */ static void null_test_success(void **state) { (void) state; /* unused */ } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(null_test_success), }; return cmocka_run_group_tests(tests, NULL, NULL); } 

我是C语言中的unit testing的新手,基本上无法设置unit testing,包括连接cmocka库等。我需要帮助才能启动并运行unit testing。

我的想法是有几个unit testing文件,而不是将所有unit testing放在一个文件中。


根据Clearer的答案进行编辑

扩大

从1个测试文件到2和3,它将至少有10个以上的文件。 寻找一些优化和表达,以便很好地扩展和易于管理。 这就是我到目前为止的情况。

 VPATH := src/math/add src/math/sub src/math/mul # split src/test path VPATH += test/math/add test/math/sub test/math/mul all: libMath clean libMath: add.o sub.o mul.o ar rcs bin/libMath add.o sub.o mul.o # suggestion? $^ test: add_test sub_test mul_test clean ./add_test ./sub_test ./mul_test add_test: add_test.o add.o $(CC) -o $@ $^ sub_test: sub_test.o sub.o $(CC) -o $@ $^ mul_test: mul_test.o mul.o $(CC) -o $@ $^ clean: $(RM) *.o %.o: %.c %.h 

这是迄今为止的观察结果。

  1. 该模式似乎就像为每个test和src文件添加一个新目标。
  2. 在先决条件和命令中将.o对象添加到libMath
  3. 在测试中添加测试可执行文件test:在先决条件和命令中使用目标

在扩大规模的同时,这种方式更好还是有更好的方法?

PS我已经删除了CFLAGS系列,它在没有它的情况下正常工作,帮助我清理并减少了一些混乱。 好吗? 如果路径不适合.h文件,我的IDE(clion)显示红色摇摆线,所以我在测试文件中使用完整路径来包含src文件。

PPS它在项目的根目录上创建测试可执行文件,如何在bin文件夹中创建所有二进制文件,然后在项目结束时删除所有二进制文件。

我会添加一个test目标。 该目标将取决于您的所有测试程序,然后应执行程序; 您可能希望添加单个目标来执行程序,只需保留一个主测试目标以确保所有目标都已执行。 每个测试程序都取决于测试所需的目标文件; 如果你正在进行加法测试,那么加法测试取决于addition.o和add_test.o。 像往常一样链接它们然后执行它们。

例:

 test: addition_test ./addition_test addition_test: add_test.o add.o $(CC) -o $@ $^ 

扩展测试

您可以通过添加两个规则并删除与测试相关的大多数其他规则来扩展测试:

 test: add_test_run sub_test_run %_run: % ./$< %_test: %.o %_test.o $(CC) -o $@ $^ 

应该做你想做的一切。 这允许并行运行测试; 您可以通过在每次运行结束时创建文件来避免运行不需要运行的测试,例如:一个日志文件,它告诉您测试运行的结果。

这应该是诀窍:

 test: add_test.log sub_test.log %.log: % ./$^ > $@ %_test: %.o %_test.o $(CC) -o $@ $^ 

您应该在清洁目标中使用$(RM)而不是rm -rf$(RM)与平台无关,而rm -rf仅适用于UNIXy平台。