CuTest官网
下面讲的是基于Windows平台的编译工具cl.exe(Visual Studio附带)的测试方式.

准备

首先建立一个test文件夹, 将CuTest.hCuTest.c丢进去;

创建入口,加入测试集

  1. 在这个目录下建立AllTests.c文件, 作为测试的入口文件, 并且将所有测试集(TestSuite)加入到测试中, 如下:
    
    #include <stdio.h>
    #include "CuTest.h"

CuSuite *StrUtilGetSuite(); //声明测试集, 还可以声明多个

void RunAllTests(void)
{
CuString output = CuStringNew();
CuSuite
suite = CuSuiteNew();

CuSuiteAddSuite(suite, StrUtilGetSuite()); //加入测试集

CuSuiteRun(suite);
CuSuiteSummary(suite, output);
CuSuiteDetails(suite, output);
printf("%s\n", output->buffer);

}

int main(void)
{
RunAllTests();
}

一般就是上面有注释的两句需要修改或者添加.
## 创建单元测试文件和测试集
假如被测试的函数是`getKey()`, 在`maintask.c`这个文件中, 并且`maintask.c`有一个对应头文件`maintask.h`
创建这个文件的测试文件`testMaintask.c`,如下:
```c
#include "maintask.h"
#include "CuTest.h"

void testGetKey(CuTest *tc) //创建单个测试
{
    //                   测试信息, 测试条件
    CuAssert(tc, "Test getKey()", getKey()); 
}

CuSuite *testSuite1() //创建测试集
{
    CuSuite *suite = CuSuiteNew();
    SUITE_ADD_TEST(suite, testGetKey); //加入单个测试
    return suite;
}

加入stub头文件

比如在maintask.c中, 除了自身对应的头文件外, 还有其他头文件,如wm_include.h, 但这些头文件涉及的整个系统, 还有很多其他函数, 我不想加入, 而是想把其中有的函数打桩掉. 那么, 在test目录下新建这个头文件wm_include.h,作为打桩文件, 里面自行加入要打桩的函数即可.

编译和运行测试(基于cl.exe)

如果test目录是和maintask.c待测文件同一级, 其头文件maintask.h在这一级, 而wm_include.htest中, 那么需要有cl/I参数将这两个目录包含进来. 如/I.\ /I..\,注意/I带的目录后面是没有空格的.

cl /I..\ /I.\ ..\maintask.c Alltests.c CuTest.c testMaintask.c

将会输出:

用于 x64 的 Microsoft (R) C/C++ 优化编译器 19.16.27032.1 版
版权所有(C) Microsoft Corporation。保留所有权利。

maintask.c
Alltests.c
CuTest.c
testMaintask.c
正在生成代码...
Microsoft (R) Incremental Linker Version 14.16.27032.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:maintask.exe
maintask.obj
Alltests.obj
CuTest.obj
testMaintask.obj

运行maintask.exe即可看到测试结果.

编译和运行测试(基于gcc.exe)

如果test目录是和maintask.c待测文件同一级, 其头文件maintask.h在这一级, 而wm_include.htest中, 那么需要有gcc-I参数将这两个目录包含进来. 如-I..`,注意-I带的目录后面是没有空格的. 要包含当前目录, 不知为何-I.\不能使用, 必须要先退上一级再下来一级才可以, 如-I..\test\
另外, 加上-g可以方便gdb进行调试.

gcc -I..\  -I..\test\ ..\maintask.c Alltests.c CuTest.c testMaintask.c

如果gcc编译没有任何问题,那么它什么都不会输出, 然后产生一个a.exe的文件.
不过gcc的代码检查要比cl强度高很多.
运行a.exe即可看到测试结果.

标签: none 阅读量: 1942

添加新评论