【问题标题】:gmock - how to mock function with noexcept specifiergmock - 如何使用 noexcept 说明符模拟函数
【发布时间】:2019-07-15 21:23:32
【问题描述】:

我需要模拟以下函数:

 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());
 ^

【问题讨论】:

    标签: c++ googletest gmock


    【解决方案1】:

    现在,从 v1.10.0 开始,使用新语法可以做到这一点。 见change lognew syntax explanation

    新语法包含一个单独的参数规范来传递限定符

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

    【讨论】:

      【解决方案2】:

      在较旧的模拟版本上,可以通过简单的技巧解决这样的 c++ 装饰:

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

      在你的例子中是

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

      使用相同的模式,您可以模拟采用非 gmock 友好参数的方法,例如 auto_ptr。您还可以创建包装器函数并将参数更改为包装器内对 gmock 友好的参数(例如 shared_ptr)。

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 2019-09-22
        • 2014-01-17
        • 2019-03-11
        • 2016-02-13
        • 2020-05-08
        • 2016-04-03
        • 2021-11-19
        • 1970-01-01
        相关资源
        最近更新 更多