我知道这是一个非常旧的帖子,但我希望如果有人在遇到这个问题时,我可以让他们的生活变得更容易一些。
你可以使用Mimicc很容易地为与GoogleTest兼容的C函数自动生成mocks。找到声明所需mock函数的头文件,“编译”它们成为mock实现对象文件,并将它们链接到测试二进制文件中,包括mock_fatal()
和mock_failure()
函数的定义,如用户指南中特别针对Google Test所述。您将需要使用Mimicc API与Mimicc生成的mocks进行交互(即,它不使用GoogleMock的API设置期望等),但它们可以舒适地与GoogleMock生成的mocks并存。
更具体地说,假设您有一个C头文件foo.h
,其中声明了您想要mock的几个函数。例如:
int magic_read(char *pBuf, const size_t sz);
int magic_write(const char *pBuf, const size_t sz);
你可以通过使用与编译生产环境中的
foo.c
相同的所有
CFLAGS
来编译
foo.h
,从而为它们创建模拟。
prompt$ mimicc -c foo.h -o mock.o --hout=foo-mock.h -DSOME_PREPROC=1 -I <your includes>
要在测试中使用此功能,请按照上面命令行调用中所示,使用foo-mock.h
中声明的API设置期望值和返回值。为Google Test包含mock_fatal()
和mock_failure()
的实现。
#include <gtest/gtest.h>
#include <memory>
std::unique_ptr<char []> mockErrStr(const char *pLocation, unsigned count, const char *pMsg)
{
const char *pFmtStr = "mock assertion failure! location: '%s',"
" iteration: %d, message: %s";
size_t n = snprintf(NULL, 0, pFmtStr, pLocation, count, pMsg);
std::unique_ptr<char []> outStrBuf(new char[n+1]);
snprintf(outStrBuf.get(), n+1, pFmtStr, pLocation, count, pMsg);
return outStrBuf;
}
void mock_failure(const char *pLocation, unsigned count, const char *pMsg)
{
ADD_FAILURE() << mockErrStr(pLocation, count, pMsg).get();
}
void mock_fatal(const char *pLocation, unsigned count, const char *pMsg)
{
FAIL() << mockErrStr(pLocation, count, pMsg).get();
exit(1);
}
TEST_F(MimiccPoC, test1)
{
char mock_ret_data[] = "HELLO WORLD";
MOCK_FUNCTIONS(foo).magic_read.expect(32);
MOCK_FUNCTIONS(foo).magic_read.andReturn(
1, mock_ret_data, sizeof(mock_ret_data));
char testRetBuf[32];
int testRes = magic_read(testRetBuf, sizeof(testRetBuf));
ASSERT_EQ(1, testRes);
ASSERT_STREQ(testRetBuf, "HELLO WORLD");
}
虽然这听起来很多,但一旦管道设置好了,你就可以自动模拟任何C或C++代码,而无需编写或维护额外的模拟代码,你只需要专注于测试。从长远来看,这会更加容易。
foobar * x = malloc(sizeof(foobar));
而不是将其强制转换为(foobar *)malloc(sizeof(foobar));
。 - Alexander Oh++
操作枚举类型的人可能会遭到应有的下场。;-) - Carey Gregory