[英]How to handle static elements with cmocka?
I am using cmocka to do some unit testing on my C-Project and I am wondering how to handle static emelents.我正在使用 cmocka 对我的 C 项目进行一些单元测试,我想知道如何处理静态元素。
Static elements are for me:静态元素适合我:
So let the function fut
be our function under test, and foo
be an other function.所以让函数fut
成为我们被测的函数,而foo
是另一个函数。 Both placed in the file bar.c
:两者都放在文件bar.c
:
static int fut(int add) {
static int sum = 0;
sum += add;
return sum;
}
int foo(int someVar){
//Some calculation on someVar...
someVar = someVar * 42;
//call subRoutine
return fut(someVar);
}
And let foo.h look like this:让 foo.h 看起来像这样:
extern int foo(int someVar);
So lets go on I'll show the problem.所以让我们继续,我将展示问题。 I would like to test the function under test by two undepended tests which pass some random values for add
.我想通过两个不相关的测试来测试被测函数,这些测试传递了一些随机值add
。 The testroutines are placed in main.c and are looking like this:测试例程放置在 main.c 中,如下所示:
void fut_test_1(void **state) {
int ret;
ret = fut(15);
assert_int_equal(ret, 15);
ret = fut(21);
assert_int_equal(ret, 36);
}
void fut_test_2(void **state) {
int ret;
ret = fut(32);
assert_int_equal(ret, 32);
ret = fut(17);
assert_int_equal(ret, 49);
}
Now I could try to compile the unit test with something like: gcc main.c foo.c -Icmocka现在我可以尝试使用以下内容编译单元测试:gcc main.c foo.c -Icmocka
There are now two problems:现在有两个问题:
The function declared as static cannot be accessed from main.c
, so the linker will stop during the build process.无法从main.c
访问声明为静态的函数,因此链接器将在构建过程中停止。
The variable inside the function which are declared as static will not be reset between the two tests.函数内部声明为静态的变量不会在两次测试之间重置。 So the fut_test_2
will fail.所以fut_test_2
会失败。
How to handle these problems with the mentioned static elements?如何处理上述静态元素的这些问题?
Based on @LPs comment and my own ideas I would like to conclude possible solutions:根据@LPs 评论和我自己的想法,我想得出可能的解决方案:
Regarding the Problem one with Functions declared as static:关于函数声明为静态的问题一:
bar.c
into the test driving main.c
by #include "foo.c"
.一种解决方案是通过#include "foo.c"
将源文件bar.c
到测试驱动main.c
。 The tests fut_test_2
and fut_test_2
could by placed into bar.c
which contains then both: The function under test fut
and the tests.测试fut_test_2
和fut_test_2
可以放入bar.c
,其中包含两个:被测函数fut
和测试。 The tests can then be made accessible by adding the declaration to foo.h
:然后可以通过将声明添加到foo.h
来访问测试:
extern int foo(int someVar); extern void fut_test_1(void **state); extern void fut_test_2(void **state);
Regarding the Problem with the static variables:关于静态变量的问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.