在C++test中,桩函数分为original, auto ,user三种类型。
original的桩函数时在原程序中定义的,auto是自动生成,user是用户自定义的。
Definition: The current definition/stub type:
• User: User provided definition/stub will be used.
• Safe: C++test's safe definition/stub will be used.
• Original: Original definition will be used.
• Auto: C++test's auto definition/stub will be used.
Note: When you first open the Stubs view, it will be empty. A message stating "Symbols data not collected" will be displayed.
• N/A (not required): Definition is not available, not needed by the linker.
• N/A: Definition is not available, but is needed by the linker (in most cases, this will result in a linker error when building the test executable).
如果是,在被测文件中调用的函数定义在头文件中,并且自定义了该函数的桩函数(user),则测试文件调用user桩函数。
所以,user>original>auto
自动生成的桩函数带有CppTest_Auto_Stub_前缀,用户自定义的桩函数是CppTest_Stub_
系统生成的安全桩函数,优先级大于原来的函数。安全桩函数是为了代替原来的一些危险函数而自定生成的。使用安全桩函数会在单元测试中避免一些问题。如果不想使用系统自动生成的桩函数,则在测试配置中,去掉安全桩函数的路径即可。
利用测试用例驱动的桩函数可以达到100%的覆盖率
例如,通常对malloc函数的覆盖率都是50%,这里利用桩函数来达到100%。
#include <string>
#include <stdlib.h>
EXTERN_C_LINKAGE void* CppTest_Stub_malloc(size_t size)
{
std::string testSuiteName = CppTest_GetCurrentTestSuiteName();
std::string testCaseName = CppTest_GetCurrentTestCaseName();
if ((testSuiteName == "AllocTestSuite") &&
(testCaseName.find("nomemory") != std::string::npos))
{
// Simulate no memory situation.
return 0;
}
return malloc(size);
}