我想给它赋值updateMode
,使它不等于SYSTEM_CAL_CONFIG
如果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()
,那么您可以有条件地编译您想要在测试中完成的任何操作:
void startCalCompute (void);
void checkSystem(void)
{
#ifdef CAL
startCalCompute();
#endif
}
void test_checkSystem (void ** state)
{
#ifdef CAL
...
#endif
}
如果您需要确保调用特定函数并且取决于运行时条件,或者如果某些函数以特定顺序调用,CMockery 中没有工具可以做到这一点。但是,在CMocka中有一个,它是 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
will not call 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