gmock - 如何模拟带有noexcept修饰符的函数

6
我需要模拟以下函数:
 virtual void fun() noexcept = 0;

是否可以使用gmock?

Gmock拥有以下宏:#define GMOCK_METHOD0_(tn, constness, ct, Method, ...)但是有一个注释:// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!此外,我不知道如何使用该宏(参数tn和ct代表什么)?

编辑

以下为模拟:

GMOCK_METHOD0_(, noexcept, ,fun, void());

使用gmock 1.7.0编译没有问题,但是当我使用gmock 1.8.1编译时,出现了编译错误:

main.cpp:17: error: expected identifier before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:17: error: expected ‘,’ or ‘...’ before ‘noexcept’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
                  ^
gmock-generated-function-mockers.h:153: in definition of macro ‘GMOCK_METHOD0_’
   constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
   ^
main.cpp:-1: In member function ‘testing::internal::MockSpec<void()> MockX::gmock_fun(const testing::internal::WithoutMatchers&, int) const’:

gmock-generated-function-mockers.h:154: error: ‘AdjustConstness_noexcept’ is not a member of ‘testing::internal’
     return ::testing::internal::AdjustConstness_##constness(this)-> \
            ^
main.cpp:17: in expansion of macro ‘GMOCK_METHOD0_’
 GMOCK_METHOD0_(, noexcept, ,fun, void());
 ^
2个回答

11

从v1.10.0版本开始,使用新的语法是可行的。 详见 变更日志新的语法解释

新的语法包含一个独立的参数规范来传递修饰符。

class MyMock {
   public:
      MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...));
};

7

在旧版本的模拟中,您可以通过简单的技巧解决这种c++修饰问题:

  1. 创建不带 noexcept 的模拟方法
  2. 创建具有正确签名的代理方法,该方法将调用模拟方法

在您的示例中,应该这样做:

class Mock : public MyInterface
{
public:
  MOCK_METHOD0(funImpl, void());
  virtual void fun() noexcept
  {
    funImpl();
  }
};

使用相同的模式,您可以模拟方法,接受不符合gmock规则的参数,例如auto_ptr。您还可以创建包装函数,并在包装器内将参数更改为符合gmock规则的类型(例如shared_ptr)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接