Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock an overloaded function with const/non

Tags:

c++

googlemock

How do I mock the following code?

class ISomeClass
{
public:
   virtual ~ISomeClass() {} = 0;
   virtual const MyType & getType() const = 0;
   virtual MyType & getType() = 0;
};

I have tried the following, but it doesn´t work. Can you please help me?

class MockSomeClass : public ISomeClass
{
public:
    using MyTypeConstRefType = const MyType&;
    using MyTypeRefType = MyType&;

public:
    MOCK_METHOD0(getType, MyTypeConstRefType(void) const);

    MOCK_METHOD0(getType, MyTypeRefType(void));
};
like image 321
0xBADF00 Avatar asked Dec 10 '15 08:12

0xBADF00


People also ask

Can a const function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.

How do you call a non-const method from the const method?

Casting away const relies on the caller only using the function on non-const objects. A potential solution is to alter the code in // .... so that it doesn't need to use the object's "current color". Add versions of all the functions you use, that take a QColor parameter instead.

How is it possible to have both const and non-const version of a function?

There are legitimate uses of having two member functions with the same name with one const and the other not, such as the begin and end iterator functions, which return non-const iterators on non-const objects, and const iterators on const objects, but if it's casting from const to do something, it smells like fish.


1 Answers

They provide a separate set of macros for const member functions ("methods"): MOCK_CONST_METHOD#. So in your case, it would be:

MOCK_CONST_METHOD0(getType, MyTypeConstRefType());

The usage is otherwise identical to MOCK_METHOD#, taking the function name in the first argument and function type in the second.

like image 134
BoBTFish Avatar answered Oct 03 '22 19:10

BoBTFish