gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:30:10 25 4
gpt4 key购买 nike

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

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

我试图 mock 上面的类(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在 SO 上有建议 some workaround你可以用它来实现这一点。它涉及处理您的 format参数以及任何可变参数以创建单个 message字符串,然后模拟一个接受 message 的函数作为一个单一的论点。

关于c++ - GMOCK 一种接受可变参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46470289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com