gmock - how to mock function with noexcept specifier
Asked Answered
K

2

6

I need to mock the following function:

 virtual void fun() noexcept = 0;

Is it possible using gmock ?

Gmock has the following macro:#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) but there is a comment: // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! Moreover I don't know how to use that macro (what the parameters tn and ct means) ?

Edit

The following mock:

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

compiles with gmock 1.7.0 but when I compile it using gmock 1.8.1 I get the compilation errors:

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());
 ^
Khano answered 15/7, 2019 at 21:23 Comment(0)
E
11

Now this is possible since v1.10.0 with the new syntax. see change log and new syntax explanation

The new syntax contains a separate argument specs to pass the qualifiers

class MyMock {
   public:
      MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...));
};
Eward answered 25/11, 2019 at 11:4 Comment(0)
F
7

On older mock versions one may workaround such a c++-decoration by simple trick:

  1. Create mock method without noexcept
  2. Create proxy method with right signature, which will call mocked method

In your example it would be

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

Using the same pattern you may mock methods taking non-gmock-friendly arguments like auto_ptr. You also create wrapper function and change arguments to gmock-friendly ones inside wrapper (like shared_ptr).

Fortunia answered 19/2, 2020 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.