单元测试运行配置

时间:2018-01-24 00:06:05

标签: c unit-testing cmocka

我需要一些帮助才能启动并运行cmocka单元测试框架。我的设置是:

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;}

生成文件

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

单元测试

测试/数学/添加/ 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 <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>

/* 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中进行单元测试并不熟悉,基本上无法设置单元测试,包括连接cmocka库等。我需要帮助才能启动并运行单元测试。

我的想法是拥有多个单元测试文件,而不是将所有单元测试放在一个文件中。

根据更清楚的答案进行修改

扩展

从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. 在先决条件和命令
  3. 中将.o对象添加到libMath
  4. 在先决条件和命令
  5. 中添加test:目标下的测试可执行文件

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

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

    P.P.S 它在项目的根目录上创建测试可执行文件,如何在bin文件夹中创建所有二进制文件,然后在项目末尾删除所有二进制文件。

1 个答案:

答案 0 :(得分:2)

我会添加一个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平台。

相关问题