简体   繁体   English

在C中检查单元测试:测试静态方法的最佳方法

[英]Check Unit testing in C: Best way to test static methods

I am using Check framework do to unit testing of my C code, and I couldn't find a proper way to test the static methods. 我正在使用Check framework对我的C代码进行单元测试,但是我找不到测试静态方法的正确方法。

My work around, is not ideal at all and would like if someone can point me in the right direction on how to do it properly. 我的工作方式根本不是理想的,并且希望有人能为我指出正确执行方法的正确方向。 My work around is simply by add #ifdef macro that changes the static methods to extern in case I pass -D DEBUG at compile time. 我的解决方法是简单地添加#ifdef宏,以防在编译时通过-D DEBUG时将静态方法更改为extern。

In the source file 在源文件中

#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize) {
#else
static inline unsigned ds_roundup_to_prime (const unsigned bsize) {
#endif

And in the header file I do 在头文件中

#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize);
#endif

Ideally source code shouldn't change to cater for unit tests. 理想情况下,源代码不应更改以适合单元测试。 Unit-test framework, should must be capable of testing the source code as it will look in production. 单元测试框架必须能够测试在生产环境中使用的源代码。

Thanks 谢谢

It's debatable whether or not static functions should be tested, as they aren't part of the public API. 是否应该测试static函数是有争议的,因为它们不是公共API的一部分。

I test static functions by including the unit-under-test, rather than linking against it: 我通过包含被测单元来测试static功能,而不是针对它进行链接:

foo.c (Unit under test) foo.c (被测单元)

static int foo(int x)
{
    return x;
}

/* ... */

test_foo.c test_foo.c

#include "foo.c"

void test_foo(void)
{
    assert( foo(42) == 42 );
}

int main(void)
{
    test_foo();
}

Compile just that test: 只是编译测试:

$ gcc -Wall -Werror -o test_foo test_foo.c
$ ./test_foo

I test static functions in the following manner. 我以以下方式测试static函数。

I have a header file called utility.h . 我有一个名为utility.h的头文件。 It has the following definition: 它具有以下定义:

#ifdef UNIT_TEST
  #define UTILITY_STATIC(DECLARATION) extern DECLARATION; DECLARATION
#else
  #define UTILITY_STATIC(DECLARATION) static DECLARATION
#endif

Every source file that has functions that are to be tested are declared as such: 具有要测试功能的每个源文件都这样声明:

#include "utility.h"
UTILITY_STATIC(void function(void));
UTILITY_STATIC(void function(void))
{
}

I have an additional header file (eg test_helper.h ), used in the unit test executable, that has the line: 我在单元测试可执行文件中使用了另外一个头文件(例如test_helper.h ),其行如下:

extern void function(void);

In this way, tests have access to function whereas source files that don't define UNIT_TEST do not. 这样,测试可以访问functiondefine UNIT_TEST源文件则不能。

Note 注意

This can be used for static variables as well. 这也可以用于static变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM