我想给updateMode赋值,使它不等于SYSTEM_CAL_CONFIG
如果updateMode 依赖于从另一个函数获得的值并且您想在测试期间控制它,那么您应该创建该函数的测试替身。 Here is a good answer explaining mocks in particular.如果完全是在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() 调用,那么您可以有条件地编译您想要在测试中完成的任何事情:
void startCalCompute (void);
void checkSystem(void)
{
#ifdef CAL
startCalCompute();
#endif
}
void test_checkSystem (void ** state)
{
#ifdef CAL
...
#endif
}
如果您需要确保调用特定函数并且取决于运行时条件,或者如果某些函数以特定顺序调用,CMockery 中没有工具可以执行此操作。然而,CMocka 中的there are 是 CMockery 的一个分支,非常相似。以下是您在 CMocka 中的操作方式:
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,测试将像这样失败:
[==========] Running 1 test(s).
[ RUN ] test_checkSystem
[ ERROR ] --- __wrap_startCalCompute function was expected to be called but was not.
test_checkSystem.c:1: note: remaining item was declared here
[ FAILED ] test_checkSystem
[==========] 1 test(s) run.
[ PASSED ] 0 test(s).
[ FAILED ] 1 test(s), listed below:
[ FAILED ] test_checkSystem