我在使用CMockery为下面显示的函数编写模拟代码时遇到问题。你能给我一些提示吗?我想测试是否调用startCalCompute
并且还要为updateMode
分配值,以使其不等于SYSTEM_CAL_CONFIG
。我只需要一个起点或提示。
foo.c
static void checkSystem(void)
{
#ifndef CAL
startCalCompute();
#endif
if( SYSTEM_CAL_CONFIG != updateMode )
{
updateLogevent();
}
...
}
testfoo.c
void Test_checkSystem( void ** state )
{
// what to do here to check if startCalCompute() is called ?
}
答案 0 :(得分:2)
我想为
module my_httpd_t 1.0; require { type httpd_t; type vmblock_t; class dir read; class file { read getattr open }; } #============= httpd_t ============== allow httpd_t vmblock_t:dir read; allow httpd_t vmblock_t:file { getattr open read }; # Generated by audit2allow # To apply this policy: ## checkmodule -M -m -o my_httpd_t.mod my_httpd_t.te ## semodule_package -o my_httpd_t.pp -m my_httpd_t.mod ## semodule -i my_httpd_t.pp ## systemctl restart httpd
分配值,使其不等于updateMode
如果SYSTEM_CAL_CONFIG
取决于您从另一个函数获得的值并且您想在测试期间控制它,那么您应该创建该函数的测试双精度。 Here is a good answer explaining mocks in particular.如果它完全在updateMode
内计算,那么测试驱动程序不应该修改它,因为它的目的只是检查整体结果。
checkSystem
checkSystem.c
/* checkSystem depends on a value returned by this function */
int getUpdateMode (void);
/* This function knows nothing about testing. It just does
whatever it was created to do. */
void checkSystem (void)
{
int updateMode = getUpdateMode ();
if (SYSTEM_CAL_CONFIG != updateMode)
{
...
}
}
test_checkSystem.c
我想测试
/* When testing checkSystem, this function will be called instead of getUpdateMode */ int mock_getUpdateMode (void); { /* Get a value from test driver */ int updateMode = (int) mock(); /* Return it to the tested function */ return updateMode; } void test_checkSystem_caseUpdateMode_42 (void ** state) { int updateMode = 42; /* Pass a value to mock_getUpdateMode */ will_return (mock_getUpdateMode, updateMode); checkSystem (); /* Call the tested function */ assert_int_equal (...); /* Compare received result to expected */ }
是否被调用
如果startCalCompute
被有条件地编译为由startCalCompute()
调用,那么你可以有条件地编译你想要在测试中完成的任何事情:
checkSystem()
如果您需要确保调用特定函数并且这取决于运行时条件,或者某些函数是按特定顺序调用的,那么CMockery中没有工具可以执行此操作。但是,there are中的CMocka,它是CMockery的一个分支,非常相似。以下是您在CMocka中的表现方式:
void startCalCompute (void);
void checkSystem(void)
{
#ifdef CAL
startCalCompute();
#endif
}
void test_checkSystem (void ** state)
{
#ifdef CAL
...
#endif
}
checkSystem.c
void startCalCompute (void);
void checkSystem (void)
{
if (...)
startCalCompute ();
}
test_checkSystem.c
现在,如果/* When testing checkSystem, this function
will be called instead of startCalCompute */
void __wrap_startCalCompute (void)
{
/* Register the function call */
function_called ();
}
void test_checkSystem (void ** status)
{
expect_function_call (__wrap_startCalCompute);
checkSystem ();
}
无法调用checkSystem
,则测试将会失败:
startCalCompute