如何测试遗留的C代码并检查哪些分支命中

时间:2013-01-16 10:21:59

标签: c visual-studio-2010 unit-testing legacy-code

我有一个包含许多大(1000+行)函数的DLL。这段代码有很多复杂的逻辑,我想确保它在维护时不会被破坏,所以我创建了一个测试工具,动态加载这个DLL并调用它的API。

我想知道一种很好的方法,可以从我的测试工具中测试代码中哪些分支符合此API。我能想到这样做的唯一方法如下:

// Pseudo test code
void doTest()
{
  loadDllToBeTested();
  dll_api_function_1();
  assert( dll_api_function_1_branches.branch1Hit == true );
  unloadDllToBeTested();
}


 // Real api in the C dll
 struct dll_api_function_1_branches
 {
   bool branch1Hit;
 }

 dll_api_function_1_branches g_dll_api_function_1_branches;

 int private_func1()
 {
     printf("Doing my private stuff\n");
     return 1;
 }

 void dll_api_function_1(void)
 {
   if ( private_func1() )
   {
     printf("doing some stuff\n");
     dll_api_function_1_branches.branch1Hit = true; // so the test code can check if we got here :(
 }
 else
 {
    printf("doing some other stuff\n");
 }

 // tons of other logic and branching...
 }

其中每个函数基本上都有一个struct,当函数内部达到某些分支时,它会设置值。将有一个这个结构的全局导出实例,测试代码必须初始化为零,然后在调用API后检查。

另请注意,我正在使用Visual Studio,因此无法在此处使用像gcov这样的工具。

1 个答案:

答案 0 :(得分:1)

LLVM项目提到了KLEE工具,它有助于创建测试用例以运行所有路径(并在流程中查找错误)。其中一些是强烈面向Unix的,它是一个当前的研究项目(粗糙边缘,需要一些装配,以及其他免责声明)。

相关问题