Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gmock - how to mock function with noexcept specifier

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());
 ^
like image 967
Irbis Avatar asked Dec 18 '22 16:12

Irbis


2 Answers

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...));
};
like image 91
Jasper Avatar answered Dec 28 '22 09:12

Jasper


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).

like image 24
Łukasz Ślusarczyk Avatar answered Dec 28 '22 11:12

Łukasz Ślusarczyk