gpt4 book ai didi

在 cmocka 中创建夹具

转载 作者:行者123 更新时间:2023-12-02 15:50:11 26 4
gpt4 key购买 nike

我正在开发一个项目 using the cmocka framework 。 cmocka主页指出

Test fixtures are setup and teardown functions that can be shared across multiple test cases to provide common functions that prepare the test environment and destroy it afterwards.

但是,docs 都没有I've read解释夹具系统的工作原理。

如果我使用如下代码运行测试

int main(void) {
const struct CMUnitTest license_tests[] = {
cmocka_unit_test(test_setup),
cmocka_unit_test(test_null_app),
cmocka_unit_test(test_null_name),
};

return cmocka_run_group_tests(license_tests, NULL, NULL);
}

我如何/在哪里可以指示 cmocka 运行安装/拆卸固定装置,以及 cmocka 有哪些功能(如果有)可以让我访问在所述固定装置中创建的内容?

最佳答案

这是一个模板单元测试文件,您可以在项目中重复使用。它满足您的所有要求

#include <stdio.h>
#include <cmocka.h>

#include "mylib.h"

// Include here all your mocked functions, see below
#include "testmocks.c"

typedef struct {
mylibobj_t* mylibobj;
} teststate_t;

/**
* This is run once before all group tests
*/
static int groupSetup (void** state) {
teststate_t* teststate = calloc(1, sizeof(teststate_t));
*state = teststate;
return 0;
}

/**
* This is run once after all group tests
*/
static int groupTeardown (void** state) {
teststate_t* teststate = *state;
free(teststate);
return 0;
}

/**
* This is run once before one given test
*/
static int testSetup (void** state) {
teststate_t* teststate = *state;
//Maybe instantiate mylibobj?
return 0;
}

/**
* This is run once after one given test
*/
static int testTeardown (void** state) {
return 0;
}

/**
* This test will success with these options
*/
void mylib_setTime_s0 (void** state) {
teststate_t* teststate = *state;
// Do your testing stuff
}

/**
* This test will fail with these options
*/
void mylib_setTime_f0 (void** state) {
teststate_t* teststate = *state;
// Do your testing stuff
}

int main (void) {
const struct CMUnitTest tests[] = {
cmocka_unit_test_setup_teardown(mylib_setTime_s0, testSetup, testTeardown),
cmocka_unit_test_setup_teardown(mylib_setTime_f0, testSetup, testTeardown),
};
return cmocka_run_group_tests(tests, groupSetup, groupTeardown);
}

testmocks.c 的存在只是为了代码组织,并且可以保存 0 到 N 对模拟函数

#define MOCKBYPASS  -7337

mylib_status_t __real_inner_function (char* id);
mylib_status_t __wrap_inner_function (char* id) {
int mock = mock();
if(mock == MOCKBYPASS)
return __real_inner_function(id);
else
return mock;
}

...

请记住,gcc 编译技巧是这些模拟正常工作的必要条件

关于在 cmocka 中创建夹具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com