GMOCK 一种接受可变参数的方法

GMOCK a method accepting variable arguments

我有一个 class 有一个接受可变参数的方法:

class MyClass
{
public:
virtual void myprint(const char* format, ...) = 0; 
};

我是想模仿上面的内容class

class Mock : public MyClass
{
public:
MOCK_METHOD1(myprint, void (const char* format, ...));
}

但它给我的编译带来了问题:

error: 'Result' in 'struct testing::internal::Function<void(const char*, ...)>' does not name a type
  MOCK_METHOD1(myprint, void (const char* format, ...));
  ^
error: incomplete type 'testing::internal::Function<void(const char*, ...)>' used in nested name specifier
 error: incomplete type 'testing::internal::Function<void(const char*, ...)>' used in nested name specifier
error: template argument 1 is invalid
error: field 'gmock1_print_15' has incomplete type 'testing::internal::FunctionMocker<void(const char*, ...)>'

如何模拟将可变参数作为参数的方法?

不幸的是,你 cannot directly mock a variadic function in Gmock:

You cannot mock a variadic function (i.e. a function taking ellipsis (...) arguments) directly in Google Mock.

The problem is that in general, there is no way for a mock object to know how many arguments are passed to the variadic method, and what the arguments' types are. Only the author of the base class knows the protocol, and we cannot look into his head.

Therefore, to mock such a function, the user must teach the mock object how to figure out the number of arguments and their types. One way to do it is to provide overloaded versions of the function.

Ellipsis arguments are inherited from C and not really a C++ feature. They are unsafe to use and don't work with arguments that have constructors or destructors. Therefore we recommend to avoid them in C++ as much as possible.

但是,您可以使用 Nemelis on SO has suggested some workaround 来实现此目的。它涉及处理您的 format 参数以及任何可变参数以创建单个 message 字符串,然后模拟一个将 message 作为单个参数接收的函数。